1. 程式人生 > >winform中通過FileStream實現將檔案上傳

winform中通過FileStream實現將檔案上傳

本例項實現功能:通過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;

            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
                        {
                            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);

                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("中,是否覆蓋原檔案?");

                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 node = 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);
            }
        }

   }
}