如何在.NET上将数据保存到网络路径?

时间:2017-12-14 11:43:19

标签: c# .net

我真的很难将数据保存到我的本地网络NAS(如果重要的是Synology DS214)。

我需要在我的程序的另一部分创建一些文件后将其存储在我的网络文件夹中,但我无法正确处理身份验证/权限。

我的代码atm是这样的:

WrapperImpersonationContext WIContext = 
    new WrapperImpersonationContext("\\\\DiskStation", "admin", "admin");

try
{
    WIContext.Enter();

    // code to select the final path simplified.
    string fileName = "file.txt"; 
    string originalPath = Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments);
    originalPath= Path.Combine(new string[] {originalPath, fileName});
    string finalPath = "\\\\DiskStation\\Virtual\\DestFolder";

    if (!Directory.Exists(finalPath))
    {
        // This goes well for whatever reason
        Directory.CreateDirectory(finalPath);
    }
    finalPath = Path.Combine(new string[] {finalPath, fileName});

    // This fails for wrong username/password
    File.Move(originalPath, finalPath);

} catch (Exception ex)
{
    // Exception showing simplified here
    MessageBox.Show(ex.ToString());
    throw;
} finally
{
    WIContext.Leave();
}

我在此处找到的WrapperImpersonationContext使用的代码: WindowsImpersonationContext made easy

当我尝试移动文件时,在我的代码中写了一个UnauthorizedAccessException: Access to the path is denied.我还尝试在网络文件夹中创建一个具有相同结果的新文件。

在查看上面链接的Michiel Vanotegem代码时,我发现调用LogonUser函数时出现身份验证错误(错误代码1326让我Win32Exception (0x80004005): The user name or password is incorrect)。

我尝试使用查看thisthis页面的WNetUseConnection函数,但是我从函数中得到没有错误(在用Michiel代码替换它之后),当我尝试移动文件我得到相同的UnauthorizedAccessException: Access to the path is denied.

我还试图摆弄传递给Impersonation Wrapper的域名,但我似乎无法使其工作。我觉得我错过了什么......有人可以指出我正确的方向或帮助我解决这个问题吗?

所有提前捐款的人。

编辑15/12/2017 11:52:我发现如果我尝试在第一次错误后立即重新运行LogonUser函数,我会得到一个不同的异常(错误87 Win32Exception (0x80004005): The parameter is incorrect

1 个答案:

答案 0 :(得分:1)

我遵循@LennartStoop建议,因此我使用从this借来的代码将using块中的代码放在try finally块而不是using (NetworkConnection netConn = new NetworkConnection("\\\\DiskStation", new NetworkCredential("admin", "admin"))) { // My code here } 中:

public class Main1
{
A a=new A();
B b=new B();
a.run();//This call run() of Thread because run() of Thread only call when class 
        //implements with Runnable not when class extends Thread.
b.run();//This not run anything because no run method found in class B but it 
        //didn't show any error.

a.start();//this call run() of Thread
b.start();//this call run() of Thread
}

class A implements Runnable{
@Override
    public void run() {
            System.out.println("A ");
    }
}

class B extends Thread {

    @Override
    public void run() {
            System.out.println("B ");
    }
}

使用这个我已经能够建立网络文件夹的连接并执行我需要的所有IO操作,因此非常适合Lennart提示:)