简体   繁体   中英

How to get actual path from string in c#

Hi am facing issue to pass path in File.Copy() method. Here I have created a string dest. While I am passing it in File.copy(), it is taking "\\" double slash. Because of this, I am getting error of illegal character. Please look into it.

string dest = (@"\" + Environment.MachineName +@"\"+ Path.Replace(@"\\",@"\")).Replace(":", "$");  //the value get -"pt-LTP-109\\C$\\Temp\\192.168.0.205\\fileFolder"
dest = dest.Replace("\\\\", @"\") +"\\"+ "filename.txt"; // the value get -"\\pt-LTP-109\\C$\\Temp\\192.168.0.205\\fileFolder\\filename.txt"                             
dest = ("\"").ToString()+dest+"\""; //the value get- "\"\\pt-LTP-109\\C$\\Temp\\192.168.0.205\\fileFolder\\filename.txt\""
    File.Copy(source, dest, true);`

That is a very complicated way of doing something so simple... To convert a normal path into a UNC path you only need to do two things:

  1. Replace : with $ (which you are doing correctly).

  2. Prepend the path with two backslashes and the machine name.

Your code can be shortened to this:

string dest = System.IO.Path.Combine(@"\\" + Environment.MachineName, Path.Replace(":", "$"), "filename.txt");

尝试

Path.GetFullPath(dest).Replace(@"\",@"\\");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM