如何以编程方式获取项目中文件的文件路径?
string fileContent = File.ReadAllText(LocalConstants.EMAIL_PATH);
我作为文本文件添加到项目中的 EMAIL_PATH。这行代码会引发异常,因为默认情况下它出于某种原因在 system32 文件夹中查找。我需要将其设置为项目目录。
如何以编程方式获取项目中文件的文件路径?
string fileContent = File.ReadAllText(LocalConstants.EMAIL_PATH);
我作为文本文件添加到项目中的 EMAIL_PATH。这行代码会引发异常,因为默认情况下它出于某种原因在 system32 文件夹中查找。我需要将其设置为项目目录。
你可以使用Path.Combine
and AppDomain.CurrentDomain.BaseDirectory
:
string fileName = "SampleFile.txt";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LocalConstants.EMAIL_PATH, fileName);
在调试模式下的测试项目中返回此路径(何时LocalConstants.EMAIL_PATH="Emails"
):
C:\****\****\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsFormsApplication1\bin\Debug\Emails\SampleFile.txt
您可以使用Environment.CurrentDirectory
请参阅:http: //msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx
供进一步阅读。
编辑*
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
会做同样的事情,也许更安全一些。
这对我有用 System.AppDomain.CurrentDomain.BaseDirectory.ToString()