我正在尝试读取一个文件(工作正常),唯一的问题是当路径中有空格时,代码崩溃并告诉我没有这样的路径。有谁知道如何逃避这些空间或其他解决方案?谢谢!
这是我的代码:
public static string ReadValue(string value)
{
try
{
FileStream propertiesFile = new FileStream(ServerLocation + FileName, FileMode.Open);
StreamReader sr = new StreamReader(propertiesFile);
string Line = sr.ReadLine();
while (Line != null)
{
if (Line.Contains(value))
{
var setting = Line.Split('=')[1];
Console.WriteLine(setting);
sr.Close();
return setting;
}
Line = sr.ReadLine();
}
sr.Close();
}
catch (IOException e)
{
Console.WriteLine("Cannot find the specified file.");
Console.WriteLine(e.ToString());
return null;
}
return null;
}
答案 0 :(得分:2)
通常情况下,带有空格的路径不应该出现问题"C:\My Directory\Files"
应该是完全正常的......也许你在ServerLocation的开头或FileName的末尾忘记斜线。
String path = Path.Combine(ServerLocation, FileName);
或者:
FileStream propertiesFile = new FileStream(ServerLocation.Trim() + FileName.Trim(), FileMode.Open);
此外,正如我的评论中所建议的,将您的循环更改为:
while ((Line = sr.ReadLine()) != null)
{
if (Line.Contains(value))
{
var setting = Line.Split('=')[1];
Console.WriteLine(setting);
sr.Close();
return setting;
}
}