在C#中执行dos命令并返回结果字符串

来源:互联网 发布:乐视有线网络设置方法 编辑:程序博客网 时间:2024/05/18 08:49

在项目中,将本地C盘的一个文件夹使用subst命令映射成了X盘,在C#代码中需要获取这个X盘在C盘中的真实路径。但是在C#中并没有找到相应的接口来获取这个结果,或许是我没有找到。在DOS中有命令subst,可以显示所有被映射的虚拟驱动盘,所以或许可以使用C#执行DOS命令来获取相应的结果。执行结果如图所示。

在这里封装了一个方法,可以用于执行任何的DOS命令,并且返回结果字符串。

 public string Execute(string dosCommand, int milliseconds)        {            string output = "";     //输出字符串            if (dosCommand != null && dosCommand != "")            {                Process process = new Process();     //创建进程对象                ProcessStartInfo startInfo = new ProcessStartInfo();                startInfo.FileName = "cmd.exe";      //设定需要执行的命令                startInfo.Arguments = "/C " + dosCommand;   //设定参数,其中的“/C”表示执行完命令后马上退出                startInfo.UseShellExecute = false;     //不使用系统外壳程序启动                startInfo.RedirectStandardInput = false;   //不重定向输入                startInfo.RedirectStandardOutput = true;   //重定向输出                startInfo.CreateNoWindow = true;     //不创建窗口                process.StartInfo = startInfo;                try                {                    if (process.Start())       //开始进程                    {                        if (milliseconds == 0)                            process.WaitForExit();     //这里无限等待进程结束                        else                            process.WaitForExit(milliseconds);  //当超过这个毫秒后,不管执行结果如何,都不再执行这个DOS命令                        output = process.StandardOutput.ReadToEnd();//读取进程的输出                    }                }                catch                {                }                finally                {                    if (process != null)                        process.Close();                }            }            return output;        }string result = Execute("subst", 1000);

补充说明:

subts只是显示本地目录映射后的驱动器,如果是服务器上的目录映射到了本地,可以使用net use命令。但是更方便的是,C#中有相应的针对于获取网络驱动器真实路径的接口方法。net use结果截图

这里是C#中相关的代码

[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]        public static extern int WNetGetConnection(            [MarshalAs(UnmanagedType.LPTStr)] string localName,            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,            ref int length);        /// <summary>        /// Given a path, returns the UNC path or the original. (No exceptions        /// are raised by this function directly). For example, "P:\2008-02-29"        /// might return: "\\networkserver\Shares\Photos\2008-02-09"        /// </summary>        /// <param name="originalPath">The path to convert to a UNC Path</param>        /// <returns>A UNC path. If a network drive letter is specified, the        /// drive letter is converted to a UNC or network path. If the         /// originalPath cannot be converted, it is returned unchanged.</returns>        public string GetPathForMappedDriveFile(string originalPath)        {            StringBuilder sb = new StringBuilder(512);            int size = sb.Capacity;            // look for the {LETTER}: combination ...            if (originalPath.Length > 2 && originalPath[1] == ':')            {                // don't use char.IsLetter here - as that can be misleading                // the only valid drive letters are a-z && A-Z.                char c = originalPath[0];                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))                {                    int error = WNetGetConnection(originalPath.Substring(0, 2),                        sb, ref size);                    if (error == 0)                    {                        DirectoryInfo dir = new DirectoryInfo(originalPath);                        string path = Path.GetFullPath(originalPath)                            .Substring(Path.GetPathRoot(originalPath).Length);                        return Path.Combine(sb.ToString().TrimEnd(), path);                    }                }            }            return originalPath;        }
另外在编写有关驱动盘信息的代码时候可能会用到的方法,查询本机上所有的驱动器的信息。
    //这句代码从系统中获取所有的硬盘信息,是系统自带的方法     SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");             ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);            int i = 0;    StringBuilder builder = new StringBuilder();            foreach (ManagementObject disk in searcher.Get())            {//硬盘类型,4为网络驱动器,3为本地驱动器,这里本地目录映射的磁盘也会当成本地驱动器看待,5为光盘驱动器                string DriveType = disk["DriveType"].ToString();                string DriveName = disk["Name"].ToString();                builder.Append(DriveType + "/" + DriveName);            }