程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> winform中通過FileStream實現將文件上傳

winform中通過FileStream實現將文件上傳

編輯:.NET實例教程

本實例實現功能:通過OpenFileDialog選擇待上傳的文件,並將所選文件的完整路徑綁定到TreeVIEw控間中顯示,然後通過FolderBrowserDialog選擇上傳的文件路徑,最後通過FileStream的方法將文件以二進制流的形式寫入到所選路徑的對應文件中。
其中:
trvFile為TreeVIEw控間,顯示待上傳的文件;lablContent為Lable控間,顯示待上傳文件的信息和上傳結果;btnSearch為Button控間,執行選擇文件的功能;btnUpload為Button控間,執行文件上傳的功能。
詳細代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication1
{
    public partial class FileUpLoad : Form
    {
        public FileUpLoad()
        {
            InitializeComponent();

            this.lablContent.Text = "附件名稱:";
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.ShowDialog();

            //得到上傳文件的完整名
            string loadFullName = ofd.FileName.ToString();

            //上傳文件的文件名
            string loadName = loadFullName.Substring(loadFullName.LastIndexOf("\\") + 1);

            //上傳文件的類型
            string loadType = loadFullName.Substring(loadFullName.LastIndexOf(".") + 1);

            this.lablContent.Text += "\n"+loadFullName;

       &nb

sp;    AddFileToTreeVIEw(loadFullName, loadName);
        }
       選擇文件完成後的,用戶界面如下圖所示:

        /// <summary>
        /// 上傳文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnUpload_Click(object sender, EventArgs e)
        {
            TreeNodeCollection tnNodeColl = trvFile.Nodes;

            int nodeCount = tnNodeColl.Count;

            int successCount = 0;

            if (nodeCount > 0)
            {
                //
                //選擇保存文件的路徑
                //
                folderBrowserDialog1.ShowDialog();

                string loadPath = folderBrowserDialog1.SelectedPath;

                string nodeText = string.Empty;

                string nodeTipText = string.Empty;

                foreach (TreeNode node in tnNodeColl)
                {
                    if (node.Checked)
                    {
                        nodeText = node.Text.ToString();

                        nodeTipText = node.ToolTipText;

                        string loadFile = loadPath + "\\"+nodeTipText;

         &            bool isExists = JudgeFileExists(loadFile, nodeTipText);

                        if (isExists)
                        {
                            byte[] btFile = FileToBinary(nodeText);

          

                  if (BinaryToFile(loadFile, btFile))
                            {
                                node.Checked = false;

                                successCount++;

                                continue;
                            }
                            else
                            {
                                break;
                            }                       
                        }
                        else
     &nbsp;                  {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                string strCue = "成功上傳" + successCount.ToString() + "個文件。\n";

                int failCount = nodeCount - successCount;

                strCue += "上傳失敗" + failCount.ToString() + "個文件。\n";

                this.lablContent.Text = strCue;
            }
            else
            {
                MessageBox.Show("請選擇要上傳的文件!");
            }
        }


     上傳地址選擇界面,如下圖所示:

功界面,如下圖所示:


        /// <summary>
        /// 將文件轉換為二進制流進行讀取
        /// </summary>
        /// <param name="fileName">文件完整名</param>
        /// <returns>二進制流</returns>
        private byte[] FileToBinary(string fileName)
        {
            try
            {
                FileStream fsRead = new FileStream(fileName, FileMode.Open, FileAccess.Read);

     &nbsp;          if (fsRead.CanRead)
                {
                    int fsSize = Convert.ToInt32(fsRead.Length);

                    byte[] btRead = new byte[fsSize];

                    fsRead.Read(btRead, 0, fsSize);

                    return btRead;
                }
                else
                {
                    MessageBox.Show("文件讀取錯誤!");
                    return null;
                }
            }
            catch (Exception ce)
            {
                MessageBox.Show(ce.Message);

                return null;
            }
        }

        /// <summary>
        /// 將二進制流轉換為對應的文件進行存儲
        /// </summary>
        /// <param name="filePath">接收的文件</param>
        /// <param name="btBinary">二進制流</param>
        /// <returns>轉換結果</returns>
        private bool BinaryToFile(string fileName, byte[] btBinary)
        {
            bool result = false;

            try
            {
                FileStream fsWrite = new FileStream(fileName, FileMode.Create, FileAccess.Write);

                if (fsWrite.CanWrite)
                {
                    fsWrite.Write(btBinary, 0, btBinary.Length);

                    MessageBox.Show("文件寫入成功!");

                    result = true;
                }
                else
                {
                    MessageBox.Show("文件些入錯誤!");
                    result = false;
                }}  
            catch (Exception ce)
            {
                MessageBox.Show(ce.Message);
                result = false;
            }

            return result;
        }

 
        /// <summary>
        /// 判斷文件是否存在
        /// </summary>
        /// <param name="fileName">文件完整的路徑名</param>
        /// <param name="nodeTipText">文件名</param>
        /// <returns>判斷結果</returns>
        private bool JudgeFileExists(string fileName, string nodeTipText)
        {

            if (File.Exists(fileName))
            {
                StringBuilder sbError = new StringBuilder();
                sbError.Append(nodeTipText + "已存在於:\n");

                sbError.Append(fileName.Substring(0, fileName.LastIndexOf("\\")) + "\n");

                sbError.Append("中,是否覆蓋原文件?");

             &nbsp;  string strSearch = MessageBox.Show(sbError.ToString(), "提示", MessageBoxButtons.YesNo).ToString();

                if (strSearch == "Yes")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }

        }
   
        /// <summary>
        /// 為樹菜單賦值,即待上傳文件的完整名
        /// </summary>
        /// <param name="fullName"></param>
        /// <param name="simpleName"></param>
        private void AddFileToTreeVIEw(string fullName, string simpleName)
        {
            TreeNodeCollection nodeCollection = trvFile.Nodes;

            TreeNode n
ode = new TreeNode();

            node.Text = fullName;

            node.ToolTipText = simpleName;

            node.Checked = true;

            nodeCollection.Add(node);

            if (nodeCollection.Count == 1)
            {
                Button btnUpload = new Button();

                btnUpload.Text = "上傳
";

                btnUpload.Click += new EventHandler(btnUpload_Click);

                panel1.Controls.Add(btnUpload);
            }
        }

   }
}



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved