.netcore 在centos上读取文件异常

在项目开发中,开发者遇到一个问题:代码在Windows环境下能够正常读取文件,但在转移到CentOS系统时出现'Could not find file'错误。原因是Windows与CentOS对文件路径的解析方式不同。通过将相对路径转换为绝对URI,解决了CentOS下文件读取的问题。修改后的代码使用Uri类创建文件的绝对路径,并通过WebRequest获取响应流来读取文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目开发、测试、演示的时候都是在windows下,一切正常;当转移到centos上读取文件则报错

Could not find file '/app/wwwroot/xxx/xxx/xxx.txt'.

原始代码:

在windows下读取文件一切正常。

string path= $"{Environment.CurrentDirectory}/wwwroot/xxx/xxx/xxx.txt";

using (StreamReader sr = new StreamReader(path, Encoding.Default))
{}

修改代码:

var file_url = new Uri($"{Environment.CurrentDirectory}/wwwroot/xxx/xxx/xxx.txt");
using (Stream stream = WebRequest.Create(file_url).GetResponse().GetResponseStream())
{
    using (StreamReader sr = new StreamReader(stream, Encoding.Default))
    {
           while (!sr.EndOfStream)
           {
                  string str = sr.ReadLine();
                   ...
            }
     }
}

使用Uri的方式,把路径转为绝对路径,centos才认

windows下长这样,centos下就不清楚了

file:///F:/Work/new/aspnet-core/src/APIHost/wwwroot/xxx/xxx/xxx.txt