我可以使用Directory.GetFiles()访问安全的网络文件夹吗?

时间:2014-07-16 16:50:34

标签: c# networking io

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

2 个答案:

答案 0 :(得分:7)

如果正在运行的用户是登录用户(具有profil加载)并且已经访问远程路径(通过输入凭据),则可能在加载了用户配置文件的情况下运行的应用程序应该访问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 
    }
}

答案 1 :(得分:0)

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

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