【C#】共享文件夹

一、配置环境

(1)设置共享文件夹
1、在需要共享的文件夹上右键,选择"属性"。
2、切换到"共享"选项卡,点击"高级共享"。
3、勾选"共享此文件夹",设置共享名称,并根据需要设置用户权限。
4、点击"权限"按钮,可以详细设置用户的读取、写入权限(账户必须有密码)。
5、设置完成后,点击"确定"应用设置。


(2)访问共享文件夹
1、在局域网内的其他计算机上,打开"运行"(Win+R),输入"\\"和共享文件夹所在计算机的IP地址,如"\\192.168.1.100"。
2、找到共享文件夹,双击进入即可访问共享资源。

 

二、访问代码

来源:https://www.cnblogs.com/xielong/p/16228945.html

public static class UploadShareFileHelper
    {
        #region C#访问远程服务器共享目录下载文件到本地或本地上传到服务器
/// <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 \\IP_ADDRESS\PATH /User:username password /PERSISTENT:YES";
                string dosLine = @"net use " + path + " /user:" + username + " " + password + " /persistent:yes";
                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">下载到本地后文件路径,包含文件扩展名</param>
        /// <param name="dst">远程服务器路径(共享文件夹路径)</param>
        /// <param name="fileName">远程服务器(共享文件夹)中的文件名称,包含扩展名</param>
        public static void TransportRemoteToLocal(string src, string dst, string fileName)
        {
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;
            FileStream inFileStream = new FileStream(dst, FileMode.Open);
            FileStream outFileStream = new FileStream(src, FileMode.OpenOrCreate);
            byte[] buf = new byte[inFileStream.Length];
            int byteCount;
            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {
                outFileStream.Write(buf, 0, byteCount);
            }
            inFileStream.Flush();
            inFileStream.Close();
            outFileStream.Flush();
            outFileStream.Close();
        }

        /// <summary>
        /// 将本地文件上传到远程服务器共享目录
        /// </summary>
        /// <param name="src">本地文件的绝对路径,包含扩展名</param>
        /// <param name="dst">远程服务器共享文件路径,不包含文件扩展名</param>
        /// <param name="fileName">上传到远程服务器后的文件扩展名</param>
        public static void TransportLocalToRemote(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);
            byte[] buf = new byte[inFileStream.Length];
            int byteCount;
            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {
                outFileStream.Write(buf, 0, byteCount);
            }

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


        /// <summary>
        /// 将本地文件上传到远程服务器共享目录(通过cmd命令方式)(发现存在权限问题)
        /// </summary>
        /// <param name="srcBytes">本地文件的文件流数组</param>
        /// <param name="targetPath">远程服务器共享文件路径目录名</param>
        /// <param name="targetName">远程服务器共享文件路径名称名</param>
        public static bool UploadLocalToRemote(byte[] srcBytes, string targetPath, string targetName)
        {
            bool result = false;
            try
            {
                //判断上传的远程服务器路径是否存在
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }
                //上传到远程服务器共享文件夹后文件的绝对路径
                string savePath = targetPath + "\\" + targetName;
                //写入文件流到文件中
                FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, srcBytes.Length, false);
                fs.Write(srcBytes, 0, srcBytes.Length);
                fs.Flush();
                fs.Close();

                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
   
        #endregion
       
    }

 

调用:

/// <summary>
        /// 测试上传和下载(访问远程服务器的共享目录)
        /// </summary>
        public static void TestUpload()
        {
            bool status = false;

            status = ConnectState(@"\\192.168.3.204\ShareFiles", "administrator", "abc@123");
            if (status)
            {
                DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.3.204\ShareFiles\");
                string filename = theFolder.ToString();
                //执行方法,方法一:读写时会有访问共享目录权限问题
                //实现将本地文件写入到远程服务器
                TransportLocalToRemote(@"D:\readme.txt", filename, "readme1.txt");
                //实现将远程服务器文件写入本地
                TransportRemoteToLocal(@"C:\serverMe1.txt", filename, "serverMe.txt");
            }
            else
            {
                Console.WriteLine("未能连接!");
            }
            Console.WriteLine("成功");
        }

 

posted @ 2024-11-18 17:47  不溯流光  阅读(103)  评论(0编辑  收藏  举报