Could not find a part of the path in File.ReadAllText, but the path exists

百般思念 提交于 2019-12-11 15:13:42

问题


I have a webservice that reference a library. This library project (C# fw v4.5) reads files like templates. In my code i have this:

File.ReadAllText(applicationDir + @"EmailTemplates\Contact.cshtml")

I'm getting applicationDir like this:

string applicationDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath) + "\\";

This is throwing the Could not find a part of the path exception but the path exists on my disc. Why this is happening? i have checked the path, the permissions and i dont have any idea why is this happening. The only thing that may be is that in the path there is a space. This is the path: C:\Work\Main\Source\Mailing System\Source\MailBLL\EmailTemplates\Contact.cshtml and in the code (debuging) i see it like this:

C:\\Work\\Main\\Source\\Mailing%20System\\Source\\MailBLL\\EmailTemplates\\Contact.cshtml

Edit/First solution:

I just figured out that the problem is the %20 on the path! i have added a replace in the applicationDir and works perfect! but i dont found this as a permanent solution, is there a way that the code does not put that %20 and instead put the space?


回答1:


probably the space between the folder name "Mailing System" is causing the issue.




回答2:


Use Path.Combine like:

File.ReadAllText(Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath) 
                              ,@"EmailTemplates\Contact.cshtml"));



回答3:


Your File.Exists(YourPath) return false.
From MSDN, here is what they say about it :

true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

Do you have permissions to access this file ?
The way you're getting your path might be the problem. Could you try this and see if it works :

File.ReadAllText(@"C:\Work\Main\Source\Mailing System\Source\MailBLL\EmailTemplates\Contact.cshtml");


来源:https://stackoverflow.com/questions/22328008/could-not-find-a-part-of-the-path-in-file-readalltext-but-the-path-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!