C#连接共享文件夹

config文件:

<appSettings>
<!--共享文件夹-->
<add key ="ShareFileUrl" value="\\8.1.30.17\FileService"/>
<add key ="ShareFileUser" value="username"/>
<add key ="ShareFilePwd" value="userpassword"/>
</appSettings>
/// <summary>
/// 返回本地文件或共享文件
/// </summary>
/// <param name="path">相对路径</param>
/// <param name="serverPath">共享服务器</param>
/// <returns></returns>
public string MapPath(string path, string serverPath = "")
{
    string ph = path;
    if (string.IsNullOrWhiteSpace(path)) return "";
    string url = ConfigHelper.GetValue("ShareFileUrl");

    if (!string.IsNullOrEmpty(serverPath))
    {
        url = serverPath;
    }

    //共享文件夹能够连接
    if (ConnectShareFileSys())
    {
        ph = path.Replace("~", url).Replace("/", "\\");
    }
    else
    {
        ph = HttpContext.Current.Server.MapPath(path);
    }

    return ph;
}

/// <summary>
/// 能否连接共享文件夹
/// </summary>
/// <returns></returns>
public bool ConnectShareFileSys()
{
    bool r = false;
    try
    {
        string url = ConfigHelper.GetValue("ShareFileUrl");//共享服务器
        string user = ConfigHelper.GetValue("ShareFileUser");//用户名
        string pwd = ConfigHelper.GetValue("ShareFilePwd");//密码
        if (string.IsNullOrEmpty(url) || user == null || pwd == null)
        {
            //throw new Exception("ShareFileUrl或ShareFileUser、ShareFilePwd未配置");
            return false;
        }


        r = ShareFileUtil.connectState(url, user, pwd);
    }
    catch (Exception ex)
    {
        log4net.LogManager.GetLogger("").Error(ex);
    }


    return r;
}
public class ShareFileUtil
{
    /// <summary>
    /// 连接远程共享文件夹
    /// </summary>
    /// <param name="path">远程共享文件夹的路径</param>
    /// <param name="userName">用户名</param>
    /// <param name="passWord">密码</param>
    /// <returns></returns>
    public static bool connectState(string path, string userName, string passWord)
    {
        bool Flag = false;
        Process proc = new Process();
        try
        {
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;
            proc.Start();
            string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
            proc.StandardInput.WriteLine(dosLine);
            proc.StandardInput.WriteLine("exit");
            while (!proc.HasExited)
            {
                proc.WaitForExit(1000);
            }
            string errormsg = proc.StandardError.ReadToEnd();
            proc.StandardError.Close();
            if (string.IsNullOrEmpty(errormsg))
            {
                Flag = true;
            }
            else
            {
                throw new Exception(errormsg);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            proc.Close();
            proc.Dispose();
        }
        return Flag;
    }

    /// <summary>
    /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
    /// </summary>
    /// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
    /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
    /// <param name="fileName">保存文件的名称以及扩展名</param>
    public static void Transport(string src, string dst, string fileName)
    {

        FileStream inFileStream = new FileStream(src, FileMode.Open);
        if (!Directory.Exists(dst))
        {
            Directory.CreateDirectory(dst);
        }
        dst = dst + fileName;
        FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
        try
        {
            byte[] buf = new byte[inFileStream.Length];

            int byteCount;

            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {
                outFileStream.Write(buf, 0, byteCount);
            }

            inFileStream.Flush();
            outFileStream.Flush();
        }
        finally
        {
            inFileStream.Close();
            outFileStream.Close();
        }

    }
}



猜你喜欢

转载自blog.csdn.net/lixiaoer757/article/details/80340939