从网络驱动器C#连接/复制

时间:2012-04-02 18:30:05

标签: c# network-programming

不完全确定如何处理此问题。我已经研究了一下,但是我做得很短。尝试连接到工作中的网络驱动器并复制出最新的文件夹(更新到项目)对我来说,目录开始为\但当我将其添加到字符串变量时,它将无法连接,并且当我不会显示试图检查它。这是一个过程吗?

这就是我所拥有的。而且在某种程度上它必须是错误的。

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 个答案:

答案 0 :(得分: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);