参数异常:C# 中的'Illegal characters in path'



执行代码时收到的错误是:'ArgumentException未处理。路径中存在非法字符。'

我正在使用以下代码访问我的.xml文件。

string appPath = Path.GetDirectoryName(System.Environment.CommandLine);
FileInfo fi = new FileInfo(appPath + @"Books.xml");

我这样做是为了控制台应用程序,而不是WinForm。一段时间以来,我一直在谷歌上搜索SO。

这是家庭作业项目的一部分。然而,这是我遇到的唯一问题。

string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
FileInfo fi = new FileInfo(Path.Combine(appPath, "Books.xml"));

System.Environment.CommandLine不返回路径-它返回为运行应用程序而执行的命令行的值。

你可能需要使用Assembly.GetExecutingAssembly().Location(正如Furqan Safdar在他的回答中所说)。

CommandLine返回的EXE路径的格式很时髦,因此需要执行以下操作:

string appPath = Path.GetDirectoryName(System.Environment.CommandLine.Trim('"', ' '));

这应该行得通。

使用此代码获取应用程序目录:

var rootDirectory = AppDomain.Current.BaseDirectory;

祝你好运!

相关内容

最新更新