【问题标题】:Can I access a secured network folder with Directory.GetFiles()?我可以使用 Directory.GetFiles() 访问安全的网络文件夹吗?
【发布时间】:2014-07-16 16:50:33
【问题描述】:

是否可以使用 Directory.GetFiles() 访问网络文件夹,我通常必须在通过资源管理器打开时输入我的凭据?

【问题讨论】:

标签: c# networking io


【解决方案1】:

如果正在运行的用户是登录用户(加载了配置文件)并且已经可以访问远程路径(通过输入凭据),那么您的应用程序(可能在加载了用户配置文件的情况下运行)应该无需任何登录即可访问 UNC 路径.

否则,你可以使用这个piece of code to logon you can find in GitHub

using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
    if (unc.NetUseWithCredentials("uncpath", user, domain, password))
    {
         //  Directory.GetFiles() here 
    }
}

【讨论】:

  • 我试过了(手动登录,然后看看它是否有效)但没有运气。我认为问题可能在于它位于我通过 VPN 访问的不同域上。
  • +1 为答案 b/c 我确信它有效,尽管我已经遵循了idlerboris 评论中的答案。
  • 正如我所提到的,我没有使用这个答案而是标记它,因为我认为它有效,我无法将idlerboris 的评论标记为答案:)
【解决方案2】:

这是可能的。我通常会生成一个进程来将凭据传递给系统。请参阅下面发布的代码,它正是这样做的。该过程完成后,您将能够使用网络共享。

public void MapPath() {
    string strServer = “ServerName”; 
    string strShare = “ServerShare”; 
    string strUsername = “ServerUsername”; 
    string strPassword = “ServerPassword”; 
    Process pNetDelete = new Process(); 
    pNetDelete.StartInfo.CreateNoWindow = true; 
    pNetDelete.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
    pNetDelete.StartInfo.UseShellExecute = false; 
    pNetDelete.StartInfo.FileName = “net”; 
    pNetDelete.StartInfo.Arguments = string.Format(“use /DELETE {0}\
    {1} /Y”,  strServer, strShare); 
    pNetDelete.Start(); 
    pNetDelete.WaitForExit(); 
    Process pNetShare = new Process(); 
    pNetShare.StartInfo.CreateNoWindow = true; 
    pNetShare.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
    pNetShare.StartInfo.UseShellExecute = false; 
    pNetShare.StartInfo.RedirectStandardError = true; 
    pNetShare.StartInfo.RedirectStandardOutput = true; 
    pNetShare.StartInfo.FileName = “net”; 
    pNetShare.StartInfo.Arguments = string.Format(“use \\{0}\{1} /u:"{2}" "{3}"”, 
            strServer, strShare, strUsername, strPassword); 
    pNetShare.Start(); 
    pNetShare.WaitForExit(); 
    string strError = pNetShare.StandardError.ReadToEnd(); 
    if (pNetShare.ExitCode != 0) 
    { 
       throw new Exception(strError);
    } 
}

【讨论】:

    猜你喜欢
    • 2020-12-28
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 2013-08-17
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多