【问题标题】:Connecting / Copying from network drive从网络驱动器连接/复制
【发布时间】:2020-08-04 19:25:09
【问题描述】:

不完全确定如何处理。我已经研究了一点,但我发现不足。尝试连接到工作中的网络驱动器并复制出最新的文件夹(更新到项目)对我来说,目录以 \ 开头,但是当我将其添加到字符串变量时,它不会连接并且不会在我显示时显示尝试检查它。有这个过程吗?

这就是我所拥有的。而且它一定是错误的。

string updir = @"\\NetworkDrive\updates\xxxxx";

public void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {

        try
        {
            //check if the target directory exists
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            //copy all the files into the new directory

            foreach (FileInfo fi in source.GetFiles())
            {
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }


            //copy all the sub directories using recursion

            foreach (DirectoryInfo diSourceDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);
                CopyAll(diSourceDir, nextTargetDir);
            }
            //success here
            copyall = true;    
        }

        catch (IOException ie)
        {
            //handle it here
            copyall = false;
        }
    }

我一直用它来复制。而且效果很好。

DateTime lastHigh = new DateTime(1900, 1, 1);
        string highDir;
        foreach (string subdir in Directory.GetDirectories(updir))
        {
            DirectoryInfo fi1 = new DirectoryInfo(subdir);
            DateTime created = fi1.LastWriteTime;

            if (created > lastHigh)
            {
                highDir = subdir;
                lastHigh = created;
            }
        }

然后找到最新的文件夹。

【问题讨论】:

  • 你能显示你使用的代码吗?
  • 我用我曾经尝试访问驱动器的内容更新了我的描述。
  • 这不能是您的全部代码。请张贴整个复制方法。某处应该有一个.Copy()

标签: c# network-programming


【解决方案1】:

您可以尝试这样的事情(指定网络共享的访问权限):

string updir = @"\\NetworkDrive\updates\somefile";

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsIdentity identity = new WindowsIdentity(username, password);
WindowsImpersonationContext context = identity.Impersonate();

File.Copy(updir, @"C:\somefile", true);

【讨论】:

  • 这最终成为了我所需要的基础。谢谢
  • 我无法让它工作。首先,第二个参数被定义为“类型”而不是密码。其次,这应该与仍然抛出 UnauthorizedAccessException 的 WindowsIdentity.GetCurrent() 相同。你是如何让它真正发挥作用的?
猜你喜欢
  • 2022-10-05
  • 2017-07-19
  • 2020-03-13
  • 2018-09-20
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
相关资源
最近更新 更多