diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dfcfd56 --- /dev/null +++ b/.gitignore @@ -0,0 +1,350 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ diff --git a/MongoDbSetup.sln b/MongoDbSetup.sln new file mode 100644 index 0000000..473d041 --- /dev/null +++ b/MongoDbSetup.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.32014.148 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDbSetup", "MongoDbSetup\MongoDbSetup.csproj", "{B155F535-8513-4DE0-A844-8C51542CDBC4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B155F535-8513-4DE0-A844-8C51542CDBC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B155F535-8513-4DE0-A844-8C51542CDBC4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B155F535-8513-4DE0-A844-8C51542CDBC4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B155F535-8513-4DE0-A844-8C51542CDBC4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0DD8AF84-9FEB-4026-A620-D9FCE4FCA00B} + EndGlobalSection +EndGlobal diff --git a/MongoDbSetup/App.config b/MongoDbSetup/App.config new file mode 100644 index 0000000..193aecc --- /dev/null +++ b/MongoDbSetup/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/MongoDbSetup/FObject.cs b/MongoDbSetup/FObject.cs new file mode 100644 index 0000000..5771677 --- /dev/null +++ b/MongoDbSetup/FObject.cs @@ -0,0 +1,750 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; +using System.IO; + +namespace XS.Core.FSO +{ + /// + /// 文件系统的处理对象 + /// + public enum FsoMethod + { + /// + /// 仅用于处理文件夹 + /// + Folder = 0, + /// + /// 仅用于处理文件 + /// + File, + /// + /// 文件和文件夹都参与处理 + /// + All + } + /// + /// FObject : 文件系统的处理类 + /// + public abstract class FObject + { + + # region "文件的读写操作" + + /// + /// 以文件流的形式读取指定文件的内容 + /// + /// 指定的文件及其全路径 + /// 返回 String + public static string ReadFile(string file) + { + string strResult = ""; + + FileStream fStream = new FileStream(file, FileMode.Open, FileAccess.Read); + StreamReader sReader = new StreamReader(fStream, Encoding.Default); + + try + { + + strResult = sReader.ReadToEnd(); + } + catch{} + finally + { + fStream.Flush(); + fStream.Close(); + sReader.Close(); + } + + return strResult; + } + + /// + /// 检查一个文件是否被占用 + /// + /// 文件的绝对路径 + /// true if [is file in use] [the specified file name]; otherwise, false. + public static bool IsFileInUse(string fileName) + { + bool inUse = true; + + FileStream fs = null; + try + { + + fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, + + FileShare.None); + + inUse = false; + } + catch + { + + } + finally + { + if (fs != null) + + fs.Close(); + } + return inUse;//true表示正在使用,false没有使用 + } + + /// + /// 以gb2312格式将一段字符串写入到指定文件(如果该文件或文件夹不存在则创建) + /// + /// 文件名和指定路径 + /// 文件内容 + /// 返回布尔值 + public static string WriteFile(string file, string fileContent) + { + FileInfo f = new FileInfo(file); + // 如果文件所在的文件夹不存在则创建文件夹 + if( !Directory.Exists(f.DirectoryName) ) Directory.CreateDirectory(f.DirectoryName); + + FileStream fStream = new FileStream(file, FileMode.Create, FileAccess.Write); + StreamWriter sWriter = new StreamWriter(fStream, Encoding.GetEncoding("gb2312")); + + try + { + sWriter.Write(fileContent); + return fileContent; + } + catch( Exception exc ) + { + throw new Exception(exc.ToString()); + } + finally + { + sWriter.Flush(); + fStream.Flush(); + sWriter.Close(); + fStream.Close(); + } + } + + /// + /// 以Utf-8格式将一段字符串写入到指定文件(如果该文件或文件夹不存在则创建) + /// + /// 文件名和指定路径. + /// 文件内容. + /// System.String. + /// + public static string WriteFileUtf8(string file, string fileContent) + { + FileInfo f = new FileInfo(file); + // 如果文件所在的文件夹不存在则创建文件夹 + if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName); + + FileStream fStream = new FileStream(file, FileMode.Create, FileAccess.Write); + StreamWriter sWriter = new StreamWriter(fStream, Encoding.UTF8); + + try + { + sWriter.Write(fileContent); + return fileContent; + } + catch (Exception exc) + { + throw new Exception(exc.ToString()); + } + finally + { + sWriter.Flush(); + fStream.Flush(); + sWriter.Close(); + fStream.Close(); + } + } + + + /// + /// 以文件流的形式将内容写入到指定文件中(如果该文件或文件夹不存在则创建) + /// + /// 文件名和指定路径 + /// 文件内容 + /// 是否追加指定内容到该文件中 + /// + public static void WriteFile(string file, string fileContent, bool Append) + { + FileInfo f = new FileInfo(file); + // 如果文件所在的文件夹不存在则创建文件夹 + if( !Directory.Exists(f.DirectoryName) ) Directory.CreateDirectory(f.DirectoryName); + + StreamWriter sWriter = new StreamWriter(file, Append, Encoding.GetEncoding("gb2312")); + + try + { + sWriter.Write(fileContent); + } + catch( Exception exc ) + { + throw new Exception(exc.ToString()); + } + finally + { + sWriter.Flush(); + sWriter.Close(); + } + } + + /// + /// 以文件流的形式将内容写入到指定文件中(如果该文件或文件夹不存在则创建)-自定义编码 + /// + /// 文件名和指定路径 + /// 文件内容 + /// 是否追加指定内容到该文件中 + /// 返回布尔值 + public static void WriteFile(string file, string fileContent, bool Append,Encoding ec) + { + FileInfo f = new FileInfo(file); + // 如果文件所在的文件夹不存在则创建文件夹 + if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName); + + StreamWriter sWriter = new StreamWriter(file, Append, ec); + + try + { + sWriter.Write(fileContent); + } + catch (Exception exc) + { + throw new Exception(exc.ToString()); + } + finally + { + sWriter.Flush(); + sWriter.Close(); + } + } + # endregion + + + # region "文件夹信息的读取" + + + /// + /// 获取指定目录下的所有目录及其文件信息 + /// + /// 指定文件夹 + /// 获取方式(支持文件或目录)。 + /// DataTable + public static DataTable getDirectoryAllInfos(string dir, FsoMethod method) + { + DataTable Dt; + + try + { + DirectoryInfo dInfo = new DirectoryInfo(dir); + Dt = getDirectoryAllInfo(dInfo, method); + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + + return Dt; + } + + + + /// + /// 获取指定目录下的所有目录及其文件信息 + /// + /// 实例化的目录 + /// 获取方式。1、仅获取文件夹结构 2、仅获取文件结构 3、同时获取文件和文件夹信息 + /// DataTable. + private static DataTable getDirectoryAllInfo(DirectoryInfo d, FsoMethod method) + { + DataTable Dt = new DataTable(); + DataRow Dr; + + Dt.Columns.Add("name"); //名称 + Dt.Columns.Add("rname"); //名称 + Dt.Columns.Add("content_type"); //文件MIME类型,如果是文件夹则置空 + Dt.Columns.Add("type"); //类型:1为文件夹,2为文件 + Dt.Columns.Add("path"); //文件路径 + Dt.Columns.Add("creatime"); //创建时间 + Dt.Columns.Add("size"); //文件大小 + + // 获取文件夹结构信息 + DirectoryInfo[] dirs = d.GetDirectories(); + foreach(DirectoryInfo dir in dirs) + { + if( method == FsoMethod.File ) + { + Dt = copyDT(Dt,getDirectoryAllInfo(dir, method)); + } + else + { + Dr = Dt.NewRow(); + + Dr[0] = dir.Name; + Dr[1] = dir.FullName; + Dr[2] = ""; + Dr[3] = 1; + Dr[4] = dir.FullName.Replace(dir.Name,""); + Dr[5] = dir.CreationTime; + Dr[6] = ""; + + Dt.Rows.Add(Dr); + + Dt = copyDT(Dt,getDirectoryAllInfo(dir, method)); + } + } + + // 获取文件结构信息 + if( method != FsoMethod.Folder ) + { + FileInfo[] files = d.GetFiles(); + foreach(FileInfo file in files) + { + Dr = Dt.NewRow(); + + Dr[0] = file.Name; + Dr[1] = file.FullName; + Dr[2] = file.Extension.Replace(".",""); + Dr[3] = 2; + Dr[4] = file.DirectoryName + "\\"; + Dr[5] = file.CreationTime; + Dr[6] = file.Length; + + Dt.Rows.Add(Dr); + } + } + + return Dt; + } + + /// + /// 将两个结构一样的 DataTable 组合成一个 DataTable + /// + /// The parent. + /// The child. + /// DataTable + public static DataTable copyDT(DataTable parent, DataTable child) + { + DataRow dr; + for (int i = 0; i < child.Rows.Count; i++) + { + dr = parent.NewRow(); + for (int j = 0; j < parent.Columns.Count; j++) + { + dr[j] = child.Rows[i][j]; + } + parent.Rows.Add(dr); + } + + return parent; + } + + + + /// + /// 获取指定文件夹的信息,如:文件夹大小,文件夹数,文件数 + /// + /// 指定文件夹路径 + /// 返回 String + public static long[] getDirInfos(string dir) + { + long[] intResult = new long[3]; + DirectoryInfo d = new DirectoryInfo(dir); + intResult = DirInfo(d); + + return intResult; + } + + + /// + /// 获取一个目录下的基本信息,大小,文件夹数 ,文件数, + /// + /// The d. + /// System.Int64[0].大小[1]文件夹数[2]文件数 + private static long[] DirInfo(DirectoryInfo d) + { + long[] intResult = new long[3]; + + long Size = 0; + long Dirs = 0; + long Files = 0; + // 计算文件大小 + FileInfo[] files = d.GetFiles(); + Files += files.Length; + foreach(FileInfo file in files) + { + Size += file.Length; + } + // 计算文件夹 + DirectoryInfo[] dirs = d.GetDirectories(); + Dirs += dirs.Length; + foreach(DirectoryInfo dir in dirs) + { + Size += DirInfo(dir)[0]; + Dirs += DirInfo(dir)[1]; + Files += DirInfo(dir)[2]; + } + + intResult[0] = Size; + intResult[1] = Dirs; + intResult[2] = Files; + return intResult; + } + + + /// + /// 获取指定目录的目录信息 + /// + /// 指定目录 + /// 获取方式。1、仅获取文件夹结构 2、仅获取文件结构 3、同时获取文件和文件夹信息 + /// 返回 DataTable + public static DataTable getDirectoryInfos(string dir, FsoMethod method) + { + DataTable Dt = new DataTable(); + DataRow Dr; + + Dt.Columns.Add("name");//名称 + Dt.Columns.Add("type");//类型:1为文件夹,2为文件 + Dt.Columns.Add("size");//文件大小,如果是文件夹则置空 + Dt.Columns.Add("content_type");//文件MIME类型,如果是文件夹则置空 + Dt.Columns.Add("createTime");//创建时间 + Dt.Columns.Add("lastWriteTime");//最后修改时间 + + // 获取文件夹结构信息 + if( method != FsoMethod.File ) + { + for(int i = 0; i < getDirs(dir).Length; i++) + { + Dr = Dt.NewRow(); + DirectoryInfo d = new DirectoryInfo(getDirs(dir)[i]); + + Dr[0] = d.Name; + Dr[1] = 1; + Dr[2] = ""; + Dr[3] = ""; + Dr[4] = d.CreationTime; + Dr[5] = d.LastWriteTime; + + Dt.Rows.Add(Dr); + } + } + + // 获取文件结构信息 + if( method != FsoMethod.Folder ) + { + for(int i = 0; i < getFiles(dir).Length; i++) + { + Dr = Dt.NewRow(); + FileInfo f = new FileInfo(getFiles(dir)[i]); + + Dr[0] = f.Name; + Dr[1] = 2; + Dr[2] = f.Length; + Dr[3] = f.Extension.Replace(".",""); + Dr[4] = f.CreationTime; + Dr[5] = f.LastWriteTime; + + Dt.Rows.Add(Dr); + } + } + + return Dt; + } + + + /// + /// 获取指定路径下的文件夹名称列表 + /// + /// 指定路径. + /// System.String[]. + private static string[] getDirs(string dir) + { + return Directory.GetDirectories(dir); + } + + /// + /// 获取指定路径下的文件名称列表 + /// + /// The dir. + /// System.String[]. + private static string[] getFiles(string dir) + { + return Directory.GetFiles(dir); + } + + # endregion + + + # region "文件系统的相应操作" + + /// + /// 判断文件或文件夹是否存在 + /// + /// 指定文件及其路径 + /// 判断方式 + /// 返回布尔值 + public static bool IsExist(string file, FsoMethod method) + { + try + { + if( method == FsoMethod.File ) + { + return File.Exists(file); + } + else if( method == FsoMethod.Folder ) + { + return Directory.Exists(file); + } + else + { + return false; + } + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + } + + # region "新建" + + /// + /// 新建文件或文件夹 + /// + /// 文件或文件夹及其路径 + /// 新建方式 + public static void Create(string file, FsoMethod method) + { + try + { + if( method == FsoMethod.File ) + { + WriteFile(file, ""); + } + else if( method == FsoMethod.Folder ) + { + Directory.CreateDirectory(file); + } + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + } + + # endregion + + + # region "复制" + + # region "复制文件" + /// + /// 复制文件,如果目标文件已经存在则覆盖掉 + /// + /// 源文件 + /// 目标文件 + public static void CopyFile(string oldFile, string newFile) + { + try + { + File.Copy(oldFile, newFile, true); + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + } + + + /// + /// 以流的形式复制拷贝文件 + /// + /// 源文件 + /// 目标文件 + /// + public static bool CopyFileStream(string oldPath, string newPath) + { + try + { + //建立两个FileStream对象 + FileStream fsOld = new FileStream(oldPath, FileMode.Open, FileAccess.Read); + FileStream fsNew = new FileStream(newPath, FileMode.Create, FileAccess.Write); + + //分别建立一个读写类 + BinaryReader br = new BinaryReader(fsOld); + BinaryWriter bw = new BinaryWriter(fsNew); + + //将读取文件流的指针指向流的头部 + br.BaseStream.Seek(0, SeekOrigin.Begin); + //将写入文件流的指针指向流的尾部 + br.BaseStream.Seek(0, SeekOrigin.End); + + while(br.BaseStream.Position < br.BaseStream.Length) + { + //从br流中读取一个Byte并马上写入bw流 + bw.Write(br.ReadByte()); + } + //释放所有被占用的资源 + br.Close(); + bw.Close(); + fsOld.Flush(); + fsOld.Close(); + fsNew.Flush(); + fsNew.Close(); + return true; + } + catch + { + return false; + } + + } + + # endregion + + # region "复制文件夹" + + /// + /// 复制文件夹中的所有内容及其子目录所有文件 + /// + /// 源文件夹及其路径 + /// 目标文件夹及其路径 + public static void CopyDirectory(string oldDir, string newDir) + { + try + { + DirectoryInfo dInfo = new DirectoryInfo(oldDir); + CopyDirInfo(dInfo,oldDir,newDir); + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + } + + private static void CopyDirInfo(DirectoryInfo od, string oldDir, string newDir) + { + // 寻找文件夹 + if( !IsExist(newDir, FsoMethod.Folder ) ) Create(newDir, FsoMethod.Folder); + DirectoryInfo[] dirs = od.GetDirectories(); + foreach(DirectoryInfo dir in dirs) + { + CopyDirInfo(dir,dir.FullName,newDir + dir.FullName.Replace(oldDir,"")); + } + // 寻找文件 + FileInfo[] files = od.GetFiles(); + foreach(FileInfo file in files) + { + CopyFile(file.FullName,newDir + file.FullName.Replace(oldDir,"")); + } + } + + # endregion + + # endregion + /// + /// 检查文件对应的目录是否存在,不存在就创建目录 + /// + /// 路径 + public static void ExistsDirectory(string sPath) + { + FileInfo f = new FileInfo(sPath); + // 如果文件所在的文件夹不存在则创建文件夹 + if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName); + } + + # region "移动" + + /// + /// 移动文件或文件夹 + /// + /// 原始文件或文件夹 + /// 目标文件或文件夹 + /// 移动方式:1、为移动文件,2、为移动文件夹 + public static void Move(string oldFile, string newFile, FsoMethod method) + { + try + { + FileInfo f = new FileInfo(newFile); + // 如果文件所在的文件夹不存在则创建文件夹 + if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName); + + + if( method == FsoMethod.File ) + { + File.Move(oldFile, newFile); + } + if( method == FsoMethod.Folder ) + { + Directory.Move(oldFile, newFile); + } + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + } + + # endregion + + + # region "删除" + + /// + /// 删除文件或文件夹 + /// + /// 文件或文件夹及其路径 + /// 删除方式:1、为删除文件,2、为删除文件夹 + public static void Delete(string file, FsoMethod method) + { + try + { + if( method == FsoMethod.File ) + { + File.Delete(file); + } + if( method == FsoMethod.Folder ) + { + Directory.Delete(file, true);//删除该目录下的所有文件以及子目录 + } + } + catch(Exception exc) + { + throw new Exception(exc.ToString()); + } + } + + + /// + /// 删除某个目录下所有文件,保留目录- 删除目录再创建相同目录 + /// + /// 目录地址 + public static void DeleteFiles(string strDir) + { + if (Directory.Exists(strDir)) + { + Directory.Delete(strDir, true); + Directory.CreateDirectory(strDir); + //Console.WriteLine("文件删除成功!"); + } + else + { + //Console.WriteLine("此目录不存在!"); + } + } + + # endregion + + # endregion + + + + + + + + } + + +} diff --git a/MongoDbSetup/Main.Designer.cs b/MongoDbSetup/Main.Designer.cs new file mode 100644 index 0000000..72db5ad --- /dev/null +++ b/MongoDbSetup/Main.Designer.cs @@ -0,0 +1,155 @@ +namespace MongoDbSetup +{ + partial class Main + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows 窗体设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.pbSetup = new System.Windows.Forms.ProgressBar(); + this.lb_del_mysql = new System.Windows.Forms.LinkLabel(); + this.label3 = new System.Windows.Forms.Label(); + this.btnSetup = new System.Windows.Forms.Button(); + this.lbPath = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.txtPort = new System.Windows.Forms.TextBox(); + this.groupBox1.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.pbSetup); + this.groupBox1.Controls.Add(this.lb_del_mysql); + this.groupBox1.Controls.Add(this.label3); + this.groupBox1.Controls.Add(this.btnSetup); + this.groupBox1.Controls.Add(this.lbPath); + this.groupBox1.Controls.Add(this.label1); + this.groupBox1.Controls.Add(this.txtPort); + this.groupBox1.Location = new System.Drawing.Point(11, 11); + this.groupBox1.Margin = new System.Windows.Forms.Padding(2); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Padding = new System.Windows.Forms.Padding(2); + this.groupBox1.Size = new System.Drawing.Size(357, 242); + this.groupBox1.TabIndex = 7; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "安装数据库"; + // + // pbSetup + // + this.pbSetup.Location = new System.Drawing.Point(7, 194); + this.pbSetup.Name = "pbSetup"; + this.pbSetup.Size = new System.Drawing.Size(333, 23); + this.pbSetup.TabIndex = 8; + // + // lb_del_mysql + // + this.lb_del_mysql.AutoSize = true; + this.lb_del_mysql.Location = new System.Drawing.Point(249, 114); + this.lb_del_mysql.Name = "lb_del_mysql"; + this.lb_del_mysql.Size = new System.Drawing.Size(71, 12); + this.lb_del_mysql.TabIndex = 7; + this.lb_del_mysql.TabStop = true; + this.lb_del_mysql.Text = "卸载MongoDb"; + this.lb_del_mysql.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lb_del_mysql_LinkClicked); + // + // label3 + // + this.label3.AutoSize = true; + this.label3.ForeColor = System.Drawing.SystemColors.MenuHighlight; + this.label3.Location = new System.Drawing.Point(5, 168); + this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(335, 12); + this.label3.TabIndex = 6; + this.label3.Text = "注:安装前确认当前目录存在db的数据库源目录,且不要带中文"; + // + // btnSetup + // + this.btnSetup.Location = new System.Drawing.Point(53, 97); + this.btnSetup.Margin = new System.Windows.Forms.Padding(2); + this.btnSetup.Name = "btnSetup"; + this.btnSetup.Size = new System.Drawing.Size(146, 47); + this.btnSetup.TabIndex = 0; + this.btnSetup.Text = "开始安装"; + this.btnSetup.UseVisualStyleBackColor = true; + this.btnSetup.Click += new System.EventHandler(this.btnSetup_Click); + // + // lbPath + // + this.lbPath.AutoSize = true; + this.lbPath.Location = new System.Drawing.Point(15, 24); + this.lbPath.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.lbPath.Name = "lbPath"; + this.lbPath.Size = new System.Drawing.Size(53, 12); + this.lbPath.TabIndex = 5; + this.lbPath.Text = "当前目录"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(15, 61); + this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(35, 12); + this.label1.TabIndex = 1; + this.label1.Text = "端口:"; + // + // txtPort + // + this.txtPort.Location = new System.Drawing.Point(53, 58); + this.txtPort.Margin = new System.Windows.Forms.Padding(2); + this.txtPort.Name = "txtPort"; + this.txtPort.Size = new System.Drawing.Size(76, 21); + this.txtPort.TabIndex = 2; + this.txtPort.Text = "27017"; + // + // Main + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(377, 264); + this.Controls.Add(this.groupBox1); + this.Name = "Main"; + this.Text = "Mongodb秒装器"; + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.ProgressBar pbSetup; + private System.Windows.Forms.LinkLabel lb_del_mysql; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Button btnSetup; + private System.Windows.Forms.Label lbPath; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox txtPort; + } +} + diff --git a/MongoDbSetup/Main.cs b/MongoDbSetup/Main.cs new file mode 100644 index 0000000..eebe42e --- /dev/null +++ b/MongoDbSetup/Main.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using XS.Core.FSO; + +namespace MongoDbSetup +{ + public partial class Main : Form + { + private string SettingInfo = @"dbpath = #数据位置# +logpath = #日志位置# +"; + public Main() + { + InitializeComponent(); + this.StartPosition = FormStartPosition.CenterScreen; + this.MaximizeBox = false;//使最大化窗口失效 + //下一句用来禁止对窗口大小进行拖拽 + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + + txtPort.ReadOnly = true; + } + + private void btnSetup_Click(object sender, EventArgs e) + { + pbSetup.Maximum = 100; + string sPath = AppDomain.CurrentDomain.BaseDirectory; + string sPan = Path.GetPathRoot(sPath); + + //string sPassWord = txtPass.Text.Trim(); + //if (string.IsNullOrEmpty(sPassWord)) + //{ + // MessageBox.Show("请输入正确的密码!"); + // return; + //} + + string sPort = txtPort.Text.Trim(); + + if (string.IsNullOrEmpty(sPort) || sPort.Length < 4 || !Tools.IsNumeric(sPort)) + { + MessageBox.Show("请输入正确的端口,端口为4位到5位的数字!"); + return; + } + + bool paortUsed = Tools.portInUse(27017); + + if (paortUsed) + { + MessageBox.Show($"端口27017已经其他程序占用!"); + return; + } + + string serviceName = "MongoDB"; + if (Tools.CheckService(serviceName)) + { + MessageBox.Show("已经存在MongoDB服务,要重新安装,请先卸载!"); + return; + } + + + + string dataPath = $@"{sPath}mongodb\data"; + string logPath = $@"{sPath}mongodb\logs\mongo.log"; + + SettingInfo = SettingInfo.Replace("#数据位置#", dataPath).Replace("#日志位置#", logPath); + + string dbSettingFile = string.Concat(sPath, "mongodb\\mongo.conf"); + + FObject.WriteFile(dbSettingFile, SettingInfo); + + + if (FObject.IsExist(dataPath, FsoMethod.Folder)) + { + MessageBox.Show("mongodb目录已经已经存在data,为了安全起见,请你备份后手动删除此目录再尝试!"); + return; + } + if (FObject.IsExist(logPath, FsoMethod.Folder)) + { + MessageBox.Show("mongodb目录已经已经存在logs,为了安全起见,请你备份后手动删除此目录再尝试!"); + return; + } + btnSetup.Enabled = false; + btnSetup.Text = "开始安装..."; + Thread threadCpuInfo = new Thread(() => + { + Action proce_update = (data) => + { + pbSetup.Value = data; + }; + Invoke(proce_update, 20); + + + FObject.Create(dataPath,FsoMethod.Folder); + FObject.Create(logPath, FsoMethod.File); + + Invoke(proce_update, 40); + + List cmds = new List(); + + cmds.Add(string.Format("cd {0}", sPan)); + cmds.Add(string.Format(@"cd {0}mongodb\bin", sPath)); + //string realPath = dbSettingFile.Replace("\\\\", "\\"); + cmds.Add($"mongod --config={dbSettingFile} --install --serviceName 'MongoDB'"); + + bool isruned = Tools.RunCmd(cmds); + if (isruned) + { + Invoke(proce_update, 80); + Tools.RunCmd("net start MongoDB"); + isruned = Tools.RunCmd(cmds); + if (isruned) + { + Invoke(proce_update, 100); + MessageBox.Show("安装完成!"); + Action action = (data) => + { + btnSetup.Enabled = true; + btnSetup.Text = "开始安装"; + }; + Invoke(action, 1); + } + } + + + }); + + + threadCpuInfo.Start(); + + + + + } + + private void lb_del_mysql_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { + bool isok = Tools.ConfirmDialog("确定要删除MongoDB的服务吗!"); + if (isok) + { + lb_del_mysql.Enabled = false; + Thread threadCpuInfo2 = new Thread(() => + { + + bool isRuned = Tools.RunCmd("net stop MongoDB"); + if (isRuned) + { + isRuned = Tools.RunCmd("SC Delete 'MongoDB'"); + if (isRuned) + { + Action action = (data) => + { + lb_del_mysql.Enabled = true; + lb_del_mysql.Text = "MongoDB已经删除"; + }; + Invoke(action, 1); + } + else + { + MessageBox.Show("旧服务删除失败"); + } + + + } + + + }); + + threadCpuInfo2.Start(); + } + } + } +} diff --git a/MongoDbSetup/Main.resx b/MongoDbSetup/Main.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MongoDbSetup/Main.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MongoDbSetup/MongoDbSetup.csproj b/MongoDbSetup/MongoDbSetup.csproj new file mode 100644 index 0000000..5873dff --- /dev/null +++ b/MongoDbSetup/MongoDbSetup.csproj @@ -0,0 +1,96 @@ + + + + + Debug + AnyCPU + {B155F535-8513-4DE0-A844-8C51542CDBC4} + WinExe + MongoDbSetup + MongoDbSetup + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + LocalIntranet + + + false + + + Properties\app.manifest + + + + + + + + + + + + + + + + + + + Form + + + Main.cs + + + + + + Main.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/MongoDbSetup/Program.cs b/MongoDbSetup/Program.cs new file mode 100644 index 0000000..0035136 --- /dev/null +++ b/MongoDbSetup/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MongoDbSetup +{ + internal static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Main()); + } + } +} diff --git a/MongoDbSetup/Properties/AssemblyInfo.cs b/MongoDbSetup/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ec9938e --- /dev/null +++ b/MongoDbSetup/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MongoDbSetup")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MongoDbSetup")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("b155f535-8513-4de0-a844-8c51542cdbc4")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MongoDbSetup/Properties/Resources.Designer.cs b/MongoDbSetup/Properties/Resources.Designer.cs new file mode 100644 index 0000000..9af725c --- /dev/null +++ b/MongoDbSetup/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace MongoDbSetup.Properties +{ + + + /// + /// 强类型资源类,用于查找本地化字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// 返回此类使用的缓存 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MongoDbSetup.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/MongoDbSetup/Properties/Resources.resx b/MongoDbSetup/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MongoDbSetup/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MongoDbSetup/Properties/Settings.Designer.cs b/MongoDbSetup/Properties/Settings.Designer.cs new file mode 100644 index 0000000..ca26355 --- /dev/null +++ b/MongoDbSetup/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MongoDbSetup.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/MongoDbSetup/Properties/Settings.settings b/MongoDbSetup/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MongoDbSetup/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MongoDbSetup/Properties/app.manifest b/MongoDbSetup/Properties/app.manifest new file mode 100644 index 0000000..c82193a --- /dev/null +++ b/MongoDbSetup/Properties/app.manifest @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MongoDbSetup/Tools.cs b/MongoDbSetup/Tools.cs new file mode 100644 index 0000000..3d383c7 --- /dev/null +++ b/MongoDbSetup/Tools.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.ServiceProcess; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MongoDbSetup +{ + internal class Tools + { + static public bool RunCmd(string cmdStr) + { + List cmds = new List(); + cmds.Add(cmdStr); + return RunCmd(cmds); + } + static public bool RunCmd(List cmds) + { + bool result = false; + try + { + using (Process myPro = new Process()) + { + myPro.StartInfo.FileName = "cmd.exe"; + myPro.StartInfo.UseShellExecute = false; + myPro.StartInfo.RedirectStandardInput = true; + myPro.StartInfo.RedirectStandardOutput = true; + myPro.StartInfo.RedirectStandardError = true; + myPro.StartInfo.CreateNoWindow = true; + myPro.Start(); + //如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义) + //string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit"); + + foreach (string cmd in cmds) + { + myPro.StandardInput.WriteLine(cmd); + } + + myPro.StandardInput.WriteLine("exit"); + + //myPro.StandardInput.WriteLine(str); + myPro.StandardInput.AutoFlush = true; + myPro.WaitForExit(); + + result = true; + } + } + catch + { + } + return result; + } + static public bool ConfirmDialog(string ShowMsg) + { + DialogResult dr = MessageBox.Show(ShowMsg, "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); + if (dr == DialogResult.OK) + { + return true; + } + else + { + return false; + } + } + static public bool CheckService(string serviceName) + { + bool bCheck = false; + + //获取windows服务列表 + ServiceController[] serviceList = ServiceController.GetServices(); + + //循环查找该名称的服务 + for (int i = 0; i < serviceList.Length; i++) + { + if (serviceList[i].DisplayName.ToString() == serviceName) + { + bCheck = true; + break; + } + } + return bCheck; + } + + static public bool portInUse(int port) + { + bool flag = false; + IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); + IPEndPoint[] ipendpoints = properties.GetActiveTcpListeners(); + foreach (IPEndPoint ipendpoint in ipendpoints) + { + if (ipendpoint.Port == port) + { + flag = true; + break; + } + } + + if (flag) + { + return true; + } + + ipendpoints = properties.GetActiveUdpListeners(); + + foreach (IPEndPoint ipendpoint in ipendpoints) + { + if (ipendpoint.Port == port) + { + flag = true; + break; + } + } + ipendpoints = null; + properties = null; + return flag; + } + + static public int StrToInt(string str, int defValue = 0) + { + if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 || !Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$")) + return defValue; + + int rv; + if (Int32.TryParse(str, out rv)) + return rv; + + return Convert.ToInt32(StrToFloat(str, defValue)); + } + static public float StrToFloat(string strValue, float defValue) + { + if ((strValue == null) || (strValue.Length > 10)) + return defValue; + + float intValue = defValue; + if (strValue != null) + { + bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); + if (IsFloat) + float.TryParse(strValue, out intValue); + } + return intValue; + } + static public bool IsNumeric(string expression) + { + if (expression != null) + { + string str = expression; + if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$")) + { + if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1')) + return true; + } + } + return false; + } + } +}