File.OpenText is adding C:\ to the front which is an error

49 Views Asked by At

I'm trying to open a file, but for some reason it's putting C:\ in front of the server name, which is not correct.

I tried two different ways:

void ParseLogFile(string serverName, string logName)
{
   string lognameFull = logName + ".txt";
   string partialPath = @"\build\logs\";
   string combinedPath = "\\" + serverName + partialPath;
   string filePath = Path.Combine(combinedPath, Path.GetFileName(logNameFull)); 

   //one way:
   StreamReader reader0 = File.OpenText(@"\mach31\"); //error: 
   System.IO.FileNotFoundException : 
   Could not find file 'C:\mach31\ (even if there was a filename here it wouldn't find it with the C)

   //another way (moved cursor to run this and not the one above):
   StreamReader reader = File.OpenText(filePath); //error: 
   System.IO.DirectoryNotFoundException: '   Could not find a part of the path 
   'C:\mach31\build\logs\SpinFileVersionStats.txt'.'
}

So no matter what the filename is, it's putting C: in front of the string. How do I prevent it from putting C there? I need the full path to our server, which doesn't have a C: in it.

I looked at open file with full UNC path I would think I wouldn't need to do what they are doing. and also open filebut I'm doing the same thing as they are, but they don't have a server name, they are using C:.

Any idea why it defaults to C: and how to fix it?

1

There are 1 best solutions below

0
Michele On BEST ANSWER

I got it to work with the uri method:

string serverPath = @"\\\\" + serverName;
string logNameFull = logName + ".txt";
string partialPath = @"\build\logs\";
string combinedPath2 = partialPath + logNameFull;
Uri serverUri = new Uri(serverPath + combinedPath2);
string finalPath = serverUri.LocalPath;

StreamReader readerb = File.OpenText(finalPath);