.netcore 在centos上读取文件异常

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

项目开发、测试、演示的时候都是在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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值