下面的代码在 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/