在文件中找不到路径的一部分.ReadAllText,但路径存在

本文关键字:路径 ReadAllText 存在 一部分 文件 找不到 | 更新日期: 2023-09-27 17:49:26

我有一个引用库的web服务。这个库项目(c# fw v4.5)像读取模板一样读取文件。在我的代码中,我有这个:

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

我得到这样的applicationDir:

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

这是抛出Could not find a part of the path异常,但路径存在于我的磁盘上。为什么会发生这种情况?我已经检查了路径,权限,我不知道为什么会发生这种情况。唯一可能的是,在路径上有一个空间。这是路径:C:'Work'Main'Source'Mailing System'Source'MailBLL'EmailTemplates'Contact.cshtml,在代码(调试)中,我看到它是这样的:

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

编辑/第一个解:

我刚刚发现问题是路径上的%20 !我已经在applicationDir中添加了一个替换,并且工作完美!但我没有发现这是一个永久的解决方案,有没有一种方法,代码不把%20,而是把空间?

在文件中找不到路径的一部分.ReadAllText,但路径存在

使用Path.Combine:

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

可能是文件夹名称"邮寄系统"之间的空格造成的问题。

您的File.Exists(YourPath)返回false。
来自MSDN,以下是他们对此的评论:

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.

您有权限访问这个文件吗?
你选择路径的方式可能就是问题所在。你可以试试这个,看看它是否有效:

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