File.OpenText 将 C:\ 添加到前面,这是一个错误

问题描述 投票:0回答:1

我正在尝试打开一个文件,但由于某种原因,它将 C:\ 放在服务器名称前面,这是不正确的。

我尝试了两种不同的方法:

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'.'
}

所以无论文件名是什么,它都会将 C: 放在字符串前面。我如何防止它把 C 放在那里?我需要我们服务器的完整路径,其中没有 C:。

我查看了打开带有完整UNC路径的文件我想我不需要做他们正在做的事情。 并且 打开文件但我正在做与他们相同的事情,但他们没有服务器名称,他们使用的是C:。

知道为什么它默认为 C: 以及如何修复它吗?

c# file
1个回答
0
投票

我让它与 uri 方法一起工作:

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);
© www.soinside.com 2019 - 2024. All rights reserved.