c# - 使用在 Linux 上运行的 .Net 2.2 核心读取文件共享上的文件内容

标签 c# linux file .net-core .net-core-2.2

下面的代码在 Windows 下工作,但在 Linux 下出现异常,其中用户主驱动器似乎被添加到尝试打开文件时获得的 LocalPath 之前。 如果我使用 FileStream,同样的问题。

在 RHEL 7.6 下测试

有人知道解决方法或根本原因吗?

必须在下面的代码片段中使实际文件共享匿名,所以请忽略路径中的任何拼写错误,它在 Windows 上工作的事实很重要。

输出是:

IsUnc True isFile True LocalPath=\\lnasvr001.partners\dfs\Analytics\suite\demo\externaldata\DemoDataset\temp\diagnose.json AbsolutePath=/dfs/Analytics/suite/demo/externaldata/DemoDataset/temp/diagnose.json

异常(exception)是:

Unhandled Exception: System.IO.FileNotFoundException: Could not find file '/home/appuser/testapp/\\lnasvr001.partners\dfs\Analytics\suite\demo\externaldata\DemoDataset\temp\diagnose.json'.
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
   at System.IO.File.InternalReadAllText(String path, Encoding encoding)
   at System.IO.File.ReadAllText(String path)

我的代码:

static void Main(string[] args)
    {
        var path = "file://lnasvr001.partners/dfs/Analytics/suite/demo/externaldata/DemoDataset/temp/diagnose.json";
        Uri uri = new Uri(path);
        Console.WriteLine($"IsUnc {uri.IsUnc} isFile {uri.IsFile} LocalPath={uri.LocalPath} AbsolutePath={uri.AbsolutePath}");
        Console.WriteLine($"File Content Length {File.ReadAllText(uri.LocalPath).Length}");
    }

最佳答案

问题是你构建路径的方式

你必须使用Path.Combine

static void Main(string[] args)
    {
        //var path = "file://lnasvr001.partners/dfs/Analytics/suite/demo/externaldata/DemoDataset/temp/diagnose.json";
        var path = Path.Combine("file:","lnasvr001.partners/dfs/Analytics/suite/demo/externaldata/DemoDataset/temp/diagnose.json");
        Uri uri = new Uri(path);
        Console.WriteLine($"IsUnc {uri.IsUnc} isFile {uri.IsFile} LocalPath={uri.LocalPath} AbsolutePath={uri.AbsolutePath}");
        Console.WriteLine($"File Content Length {File.ReadAllText(uri.LocalPath).Length}");
    }

关于c# - 使用在 Linux 上运行的 .Net 2.2 核心读取文件共享上的文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55028794/

相关文章:

file - 将文件内容显示为二进制

c# - 在 C# 中建立 P2P 连接

linux - 无法访问目录

java - 这种方法以某种方式删除了我的文件内容,但没有明显的原因

file - 如何读取文件而不将其加载到内存中,例如 D 中的 Delphi TFileStream 类?

c++ - 操作系统原生 2D API 与 OpenGL

c# - 哪些是 C# 原生内置设计模式?

c# - 为什么 ForEach 方法仅在 List<T> 集合上?

C#,将数字字符串显示为原始格式的数字

python - 平均时间和 CPU Linux