Code_Beginner
Code_Beginner

Reputation: 79

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);`

Upvotes: 1

Views: 217

Answers (2)

Visual Vincent
Visual Vincent

Reputation: 18310

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");

Upvotes: 2

user3044096
user3044096

Reputation: 171

Try

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

Upvotes: 0

Related Questions