【问题标题】:access denied while accessing a file in windows shared location访问 Windows 共享位置中的文件时访问被拒绝
【发布时间】:2023-02-10 14:04:22
【问题描述】:

所以有两台计算机(A 和 B)连接用于文件共享。 A 需要访问 B 的文件夹。 在 comp A 中,Windows 资源管理器中的路径正在运行 \B\共享文件夹\文件.txt 成功能够打开文件。 但是在我的 .net 应用程序中 .net framework 4.7.2 相同的路径不起作用。访问被拒绝。

请让我知道如何访问此文件。

尝试使用网络凭据。没用。

【问题讨论】:

    标签: c# .net windows networking shared


    【解决方案1】:

    要访问应用程序中的 UNC 文件共享,您必须提供凭据以允许应用程序访问共享。

    是这样的:

    string filePath = @"\servershareile.txt";
    string username = "username";
    string password = "password";
    
    try
    {
        using (NetworkCredential networkCredential = new NetworkCredential(username, password))
        {
            using (FileStream fileStream = File.OpenRead(filePath))
            {
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    string fileContents = reader.ReadToEnd();
                    Console.WriteLine("File contents: {0}", fileContents);
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading file: {0}", ex.Message);
    }
    

    如果您使用的是旧版本的 .NET,它可能不支持对非一次性对象使用 using 语句。你应该改用这个:

    try
    {
        NetworkCredential networkCredential = new NetworkCredential(username, password);
        FileStream fileStream = File.OpenRead(filePath);
        using (StreamReader reader = new StreamReader(fileStream))
        {
            string fileContents = reader.ReadToEnd();
            Console.WriteLine("File contents: {0}", fileContents);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading file: {0}", ex.Message);
    }
    

    【讨论】:

    • 似乎 NetworkCredentials 不能隐式转换为 System.IDisposable 以用于 using 语句
    • 它不工作仍然访问被拒绝。不使用声明
    • 您使用什么凭据?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 2012-04-05
    • 2013-05-26
    • 2012-11-07
    相关资源
    最近更新 更多