2012-10-05 27 views
1

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

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

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

我这样做的控制台应用程序,而不是一个WinForm。我一直在穷尽地搜索,并搜索了一段时间。

这是一个家庭作业项目的一部分。但这是我遇到的唯一问题。

+2

将'appPath'打印到控制台,看看它是什么 –

+0

你在CommandLine上传递的路径是什么 –

回答

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

这只有在上面的代码在exe中才有效,这可能足够了。不要从一个DLL中完成它,除非它在同一个目录:) –

+0

很棒!谢谢!如果有人遇到这个解决方案,请注意......确保包含'using System.Reflection' = P – user1721879

1

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

您可能需要使用Assembly.GetExecutingAssembly().Location(如Furqan Safdar在his answer中发布)。

+1

要小心。当前目录不一定与包含可执行文件的目录相同。 –

+0

@DavidHeffernan - 确实如此,尽管我无法想起推荐的方式来获取应用程序路径。 – Oded

0

通过的CommandLine返回的EXE路径的格式是时髦的,所以你需要做这样的事情:

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

这应该工作。

0

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

var rootDirectory = AppDomain.Current.BaseDirectory; 

祝你好运!

相关问题