C# 向共享文件夹上传文件

14 篇文章 0 订阅
5 篇文章 0 订阅

研究了好久,才做成,以此做个日志。

一共两种方法

第一种:使用dos命令

        /// <summary>
        /// 连接共享文件
        /// </summary>
        /// <param name="path">共享文件地址</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns>true:连接成功 false:连接失败</returns>
        public bool ConnectState(string path, string userName, string passWord, int islog)
        {
            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 \\192.168.1.205\ipc$ 12345/user:ftpuser";
                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
                {
                    if (islog > 0)
                        com.log("ConnectState", "连接共享文件信息:" + errormsg);
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                if (islog > 0)
                    com.log("ConnectState", "连接共享文件出错:" + ex.Message);
                //throw ex;
                Flag = false;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }

            return Flag;
        }

        /// <summary>
        /// 上传文件到共享文件夹
        /// </summary>
        /// <param name="sourceFile">本地文件</param>
        /// <param name="remoteFile">远程文件</param>
        public bool UpLoadFile(string sourceFile, string remoteFile, int islog)
        {
            //判断文件夹是否存在 ->不存在则创建
            var targetFolder = Path.GetDirectoryName(remoteFile);
            DirectoryInfo theFolder = new DirectoryInfo(targetFolder);
            if (theFolder.Exists == false)
            {
                theFolder.Create();
            }

            var flag = true;

            try
            {
                WebClient myWebClient = new WebClient();
                NetworkCredential cread = new NetworkCredential();
                myWebClient.Credentials = cread;
                
                using (FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader r = new BinaryReader(fs))
                    {
                        byte[] postArray = r.ReadBytes((int)fs.Length);
                        using (Stream postStream = myWebClient.OpenWrite(remoteFile))
                        {
                            if (postStream.CanWrite == false)
                            {
                                //LogUtil.Error($"{remoteFile} 文件不允许写入~");
                                if (islog > 0)
                                    com.log("UpLoadFile", remoteFile + " 文件不允许写入~");
                                flag= false;
                            }

                            postStream.Write(postArray, 0, postArray.Length);
                        }
                    }
                }

                return flag;
            }
            catch (Exception ex)
            {
                // string errMsg = $"{remoteFile}  ex:{ex.ToString()}";
                //LogUtil.Error(errMsg);
                //Console.WriteLine(ex.Message);
                if (islog > 0)
                    com.log("UpLoadFile", "上传文件到共享文件夹:" + ex.Message);
                return false;
            }
        }

使用这个方法之前,先打开cmd窗口,用dos命令运行是否正常

命令:打开连接:net use \\IP地址\ipc$ 密码/user:用户名  注意:只有三个空格

          删除连接:net use \\IP地址\ipc$ 密码/user:用户名\del

net use错误解决方案:

            1.错误号5,拒绝访问:很可能你使用的用户不是管理员权限的,先提升权限;
             2.错误号51,Windows无法找到网络路径:网络有问题;
             3.错误号53,找不到网络路径:ip地址错误;目标未开机;目标lanmanserver服务未启动;目标有防火墙(端口过滤);
             4.错误号67,找不到网络名:你的lanmanworkstation服务未启动或者目标删除了ipc$;
             5.错误号1219,提供的凭据与已存在的凭据集冲突:你已经和对方建立了一个ipc$,请删除再连;
             6.错误号1326,未知的用户名或错误密码:原因很明显了;

  • WinXP:控制面板-〉文件夹选项-〉察看-〉简单的文件共享去掉选取。然后再尝试连接。果真是这个“简单文件共享”搞的鬼,把它取消就可以了。简单文件共享会把网络连接权限都归为 guest连接,是无法访问C$等管理共享的

  • win2003:运行->输入secpol.msc,打开本地安全设置->本地策略->安全选项->选择"网络安全:LAN管理器身份验证级别"的属性修改为“发送LM和NTLM响应”即可~

  • WIN7:是安全设置有一项要设置!本地安全策略-本地策略-安全选项-网络安全:LAN管理器身份验证级别,默认是“没有定义”,更改为“发送LM和NTLM响应!
    重启组策略:cmd:gpupdate
     

  • 或者Guest用户取消禁用

             7.错误号1792,试图登录,但是网络登录服务没有启动:目标NetLogon服务未启动;
             8.错误号2242,此用户的密码已经过期:目标有帐号策略,强制定期要求更改密码.

第二种方法:

        /// <summary>
        /// 上传文件:要设置共享文件夹是否有创建的权限,否则无法上传文件
        /// </summary>
        /// <param name="fileNamePath">本地文件路径</param>
        /// <param name="urlPath">共享文件夹地址</param>
        /// <param name="User"></param>
        /// <param name="Pwd"></param>
        /// <param name="islog"></param>
        /// <returns></returns>
        public bool UpLoadFile2(string fileNamePath, string urlPath, string User, string Pwd, int islog)
        {
            var flag = false;
            string newFileName = fileNamePath.Substring(fileNamePath.LastIndexOf(@"\") + 1);//取文件名称
            //MessageBox.Show(newFileName);
            if (urlPath.EndsWith(@"\") == false) urlPath = urlPath + @"\";

            urlPath = urlPath + newFileName;

            WebClient myWebClient = new WebClient();
            NetworkCredential cread = new NetworkCredential(User, Pwd, "Domain");
            myWebClient.Credentials = cread;
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);

             Stream postStream =null;
            try
            {
                byte[] postArray = r.ReadBytes((int)fs.Length);
                 postStream = myWebClient.OpenWrite(urlPath);
                // postStream.m
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    //MessageBox.Show("文件上传成功!", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    flag= true;
                }
                else
                {
                    //MessageBox.Show("文件上传错误!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    flag= false;
                }

                postStream.Close();
                return flag;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "错误");
                if (islog > 0)
                    com.log("UpLoadFile", "上传文件到共享文件夹:" + ex.Message);
                if (postStream != null)
                    postStream.Close();
                return false;
            }

        }

一开始直接打开文档窗口,输入共享文件地址访问是没有问题的,代码连接却总是报错,估计跟Guest被禁止的原因

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值