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

时间:2019-03-06 17:20:10

标签: 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

例外是:

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}");
    }

1 个答案:

答案 0 :(得分:0)

问题在于构建路径的方式

您必须使用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}");
    }