连接/复制网络驱动器

4

我不太确定如何处理这个问题。我已经做了一些研究,但是没有结果。我想要连接到工作中的网络驱动器,并拷贝最新的文件夹(项目更新)。对于我来说,目录以 \ 开始,但是当我将它添加到一个字符串变量时,它无法连接并且在尝试检查时也无法显示。这是否有一个解决方法?

这是我的代码。但是它肯定有问题。

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

并且要找到最新的文件夹。


1
你能展示一下你使用的代码吗? - Msonic
我已经更新了我的描述,其中包括我尝试访问驱动器所使用的内容。 - David Brewer
这不可能是你所有的代码。请发布整个复制方法。应该有一个 .Copy() 函数。 - Msonic
类似问题:https://dev59.com/aEjSa4cB1Zd3GeqPI9vi - TcKs
1个回答

4
您可以尝试像这样使用(为网络共享指定访问权限):
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);

这最终成为了我所需的基础。谢谢。 - David Brewer
2
我无法让它工作。首先,第二个参数被定义为“类型”,而不是密码。其次,这应该与WindowsIdentity.GetCurrent()相同,但仍会抛出UnauthorizedAccessException异常。你实际上是如何让它工作的? - Wouter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接