C# 基本目录-路径中的非法字符

C# 基本目录-路径中的非法字符,c#,appdomain,C#,Appdomain,我在一行中遇到问题,在该行中找到了基本目录(即.exe本身的位置),并且读取了其中文本文件中的一行 代码中的这一行出现了“路径中的非法字符”错误: StreamReader sr = new StreamReader(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\Parameters.txt")); 这可能是因为我将StreamReader()的参数格式化错误(可能是AppDomain.CurrentDomain.Base

我在一行中遇到问题,在该行中找到了基本目录(即.exe本身的位置),并且读取了其中文本文件中的一行

代码中的这一行出现了“路径中的非法字符”错误:

StreamReader sr = new StreamReader(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\Parameters.txt"));
这可能是因为我将
StreamReader()
的参数格式化错误(可能是
AppDomain.CurrentDomain.BaseDirectory
),但我不能确定,因为没有太多关于AppDomain的其他材料

任何帮助都将不胜感激。

请尝试下面的代码

var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Parameters.txt");
此函数还有其他重载,例如

Combine(String[])           //Combines an array of strings into a path.
Combine(String, String)     //Combines two strings into a path.
Combine(String, String, String)             //Combines three strings into a path.
Combine(String, String, String, String)     //Combines four strings into a path.

请参见从路径中删除
'\'

StreamReader sr = new StreamReader(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Parameters.txt"));
AppDomain.CurrentDomain.BaseDirectory+“Parameters.txt”
->这将返回如下所示的正确路径

路径:
\Visual Studio 2010\Projects\Sample\Sample\bin\Release\Parameters.txt


因此,在该路径中不需要“\”采用
字符串的
StreamReader
构造函数的重载是文件名,而不是内容


改为使用
StringReader
,或者删除
文件.ReadAllText

你不能这样做
“\Parameters.txt”
。做
“\\Parameters.txt”
“/Parameters.txt”
^我也试过了。它仍然抛出同样的错误。我现在已经发现了这个问题,请看我的回答:)谢谢。完美答案。我会投票支持这个答案,但我还没有足够的代表权。