C# 获取当前项目中文件的文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10704444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get File Path of A File In Your Current Project
提问by Nick LaMarca
How do I programmically get the File Path of a File In my project?
如何以编程方式获取项目中文件的文件路径?
string fileContent = File.ReadAllText(LocalConstants.EMAIL_PATH);
The EMAIL_PATH I added to my project as a text file. This line of code throws an exception because by default it is looking in the system32 folder for some reason. I need to set it to the projects directory.
我作为文本文件添加到我的项目中的 EMAIL_PATH。这行代码抛出异常,因为默认情况下它出于某种原因在 system32 文件夹中查找。我需要将它设置为项目目录。
采纳答案by Tim Schmelter
You could use Path.Combineand AppDomain.CurrentDomain.BaseDirectory:
你可以使用Path.Combine和AppDomain.CurrentDomain.BaseDirectory:
string fileName = "SampleFile.txt";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LocalConstants.EMAIL_PATH, fileName);
Returns in a test project in debug mode this path(when LocalConstants.EMAIL_PATH="Emails"):
在调试模式下的测试项目中返回此路径(当LocalConstants.EMAIL_PATH="Emails"):
C:\****\****\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsFormsApplication1\bin\Debug\Emails\SampleFile.txt
回答by dtsg
You can use Environment.CurrentDirectory
您可以使用 Environment.CurrentDirectory
See: http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx
请参阅:http: //msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx
For further reading.
供进一步阅读。
edit*
编辑*
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Will do the same and is perhaps a little safer.
会做同样的事情,也许更安全一点。
回答by Kapil
This worked for me System.AppDomain.CurrentDomain.BaseDirectory.ToString()
这对我有用 System.AppDomain.CurrentDomain.BaseDirectory.ToString()

