使用账号密码访问文件夹

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XianCheng
{
    public class ConnecteFile
    {
        Process p = CreateP();
        /// <summary>
        ///链接远程文件 
        /// </summary>
        /// <param name="path">远程文件夹</param>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        public void GetAccessControl(string path, string user, string pwd)
        {
            p.Start();
            p.StandardInput.WriteLine(@"Net Use {0} /del", path); //必须先删除,否则报错
            p.StandardInput.WriteLine(@"Net Use {0} ""{1}"" /user:{2}", path, pwd, user);
            p.StandardInput.WriteLine("exit"); //如果不加这句WaitForExit会卡住
            p.WaitForExit();
            p.Close();
        }

        /// <summary>
        /////关闭远程文件 
        /// </summary>
        /// <param name="path"></param>
        public void CloseAccessControl(string path)
        {          
            p.Start();
            p.StandardInput.WriteLine(@"Net Use {0} /del", path); //必须先删除,否则报错
            p.StandardInput.WriteLine("exit"); //如果不加这句WaitForExit会卡住
            p.WaitForExit();
            p.Close();
        }
        //向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="fullPath">完整的文件夹名字(10.85.17.102+DirectoryName)</param>
        public static void Transport(string fullPath)
        {
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }
        }
        public static Process CreateP()
        {
            Process pcs = new Process();
            pcs.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            pcs.StartInfo.UseShellExecute = false;
            pcs.StartInfo.RedirectStandardInput = true;
            pcs.StartInfo.RedirectStandardOutput = true;
            pcs.StartInfo.CreateNoWindow = true;
            return pcs;
        }
    }
}
ConnecteFile类

 

 static void Main(string[] args)
        {
            ConnecteFile cf = new ConnecteFile();
            string strPath = "\\\\10.11.11.111\\FindPosition";//要访问的路径
            string strUserName = @"username";//账号
            string strPWD = "password";//密码
            cf.GetAccessControl(strPath, strUserName, strPWD);

            string fullDirPath = "\\\\11.11.11.111\\FindPosition\\vichin";
            if (!Directory.Exists(fullDirPath))//创建文件夹
            {
                Directory.CreateDirectory(fullDirPath);
            }            
        }
控制台代码

 

大体思路:使用 win+R 打开运行的窗口→打开命令窗口,在命令窗口中,通过账号密码与远程服务器进行连接,连上去之后,就可以像正常操作文件一样,对文件进行操作了。

posted @ 2018-03-09 15:41  水墨晨诗  阅读(239)  评论(0编辑  收藏  举报