窗体上传文件方式

来源:互联网 发布:手机怎么在淘宝上购物 编辑:程序博客网 时间:2024/06/03 16:43
private void btnFileUpload_Click(object sender, EventArgs e)        {            openFileDialog1.ShowDialog();            btnFileUpload.Text = openFileDialog1.FileName;            string path= Path.GetFullPath(openFileDialog1.FileName);            int ilength=Directory.GetCurrentDirectory().IndexOf("\\bin");            string savepath = Directory.GetCurrentDirectory().Substring(0, ilength) + "\\Manage";//需要确定上传文件夹,现在默认在Manage文件下            UpLoadFile(path, savepath, false);        }        public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)        {            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);            string NewFileName = fileName;            if (IsAutoRename)            {                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));            }            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);            if (uriString.EndsWith("/") == false) uriString = uriString + "/";            uriString = uriString + NewFileName;            ///  创建WebClient实例            WebClient myWebClient = new WebClient();            myWebClient.Credentials = CredentialCache.DefaultCredentials;            try            {                // 要上传的文件                FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);                BinaryReader r = new BinaryReader(fs);                byte[] postArray = r.ReadBytes((int)fs.Length);                Stream postStream = myWebClient.OpenWrite(uriString, "PUT");                try                {                                        if (postStream.CanWrite)                    {                        postStream.Write(postArray, 0, postArray.Length);                        postStream.Close();                        fs.Dispose();                    }                    else                    {                        postStream.Close();                        fs.Dispose();                    }                }                catch                 {                    postStream.Close();                    fs.Dispose();                }                finally                {                    postStream.Close();                    fs.Dispose();                }            }            catch            {                MessageBox.Show("上传失败!","系统提示");            }        }

0 0
原创粉丝点击