C#文件替换助手(续)

原文地址:http://blog.csdn.net/hk_5788/article/details/52313100


1、这次修改了部分 交互 功能。新增清除替换源文件 、 去除程序启动提示、使用线程完成替换文件

     效果图:



2、线程源码

        #region 线程执行替换文件
        /// <summary>
        /// 替换文件
        /// </summary>
        private void ThreadReplaceFile()
        {
             替换文件
            string tempPath = tbAimPath.Text;

             遍历替换源文件
            getAllFiles(tempPath + "\\");

             ---提示
            MessageBox.Show("本次替换文件个数: " + iReplaceCount.ToString());
        }

        #endregion


3、详细源码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace replaceFile
{
    public partial class Form1 : Form
    {
        #region 属性
        /// <summary>
        ///  源文件
        /// </summary>
        private string strAimReplaceName = string.Empty;

        /// <summary>
        /// 源文件路径
        /// </summary>
        private string strAimReplaceFilePath = string.Empty;

        /// <summary>
        ///  替换 文件个数
        /// </summary>
        private int iReplaceCount = 0;
        #endregion

        #region 构造函数
        public Form1()
        {
            InitializeComponent();
        }
        #endregion

        #region 控件函数
        /// <summary>
        /// 窗口加载函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 浏览按钮被单击,添加 替换目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScan_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "请选择目录";
             获取选择的路径
            if (DialogResult.OK == folderBrowserDialog1.ShowDialog())
            {
                 显示添加的目录
                tbAimPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        /// <summary>
        /// 窗口dragDrop事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
             固定写法,不用改
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 获取万文件名和文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
             获取文件路径(含有文件名及文件格式)
            string filePath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();

            //全路径赋值
            this.strAimReplaceFilePath = filePath;

            // 获取文件名
            this.strAimReplaceName = this.strAimReplaceFilePath.Remove(0, this.strAimReplaceFilePath.LastIndexOf("\\") + 1);

             显示获取的文件名
            tbOrignFileName.Text = filePath;
        }

        --------------------------------------------------------------------
        获取指定的目录中的所有文件(包括文件夹)
        public void getAllFiles(string directory) 
        {
            获取指定的目录中的所有文件(不包括文件夹)
            this.getFiles(directory);

            获取指定的目录中的所有目录(文件夹)
            this.getDirectory(directory);
        }

        获取指定的目录中的所有文件(不包括文件夹)
        public void getFiles(string directory) 
        {
            string[] path = System.IO.Directory.GetFiles(directory);
            for (int i = 0; i < path.Length; i++)
            {
                 判断是否含有指定的文件名
                if (path[i].Contains(this.strAimReplaceName))
                {
                    iReplaceCount += 1;
                     替换文件
                    File.Copy(this.strAimReplaceFilePath, path[i], true);

                     显示文件名
                    lbMessage.Items.Add("替换文件:>  " + path[i]);
                }
            }
              
        }

        获取指定的目录中的所有目录(文件夹)
        public void getDirectory(string directory) 
        {
            string[] directorys = System.IO.Directory.GetDirectories(directory);
            如果该目录总没有其他文件夹
            if (directorys.Length <= 0) 
            {
                return;
            }
            else
            {
                for (int i = 0; i < directorys.Length; i++)
                {
                    getAllFiles(directorys[i]);
                }
            }
        }
        =====================================================

        /// <summary>
        /// 替换按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReplace_Click(object sender, EventArgs e)
        {
            try
            {
                 检查路径是否合理
                if (tbAimPath.Text == string.Empty)
                {
                    MessageBox.Show("替换路径不能为空");
                    return;
                }
                 检查文件是被否添加了
                if (tbOrignFileName.Text == string.Empty)
                {
                    MessageBox.Show("替换源文件没有选择");
                    return;
                }

                string tempStr = this.strAimReplaceFilePath;
                 比较助手的路径 与  替换源文件是否在同一个目录。原则:不能在同一个目录下
                if (Environment.CurrentDirectory == tempStr.Remove(tempStr.LastIndexOf("\\") + 1, this.strAimReplaceName.Length))
                {
                    MessageBox.Show("助手不能与替换源文件在同一个目录下");
                    return;
                }

                清屏
                this.ClearLixtBox();

                 替换文件
                string tempPath = tbAimPath.Text;

                 遍历替换源文件
                getAllFiles(tempPath + "\\");
                MessageBox.Show("本次替换文件个数: " + this.iReplaceCount.ToString());

                 计数器清零
                this.iReplaceCount = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show("其他异常: " + ex.Message);
                this.Close();
                //throw;
            }
        }


        /// <summary>
        ///  清除listbox中的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearListBox_Click(object sender, EventArgs e)
        {
             清除数据
            ClearLixtBox();
        }

        /// <summary>
        /// 清除替换源文件输入框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearOrignFile_Click(object sender, EventArgs e)
        {

            if (tbOrignFileName.Text != string.Empty)
            {
                tbOrignFileName.Text = string.Empty;
            }
        }
        #endregion

        #region 清除listbox
        /// <summary>
        /// 清除listbox
        /// </summary>
        private void ClearLixtBox()
        {
             有内容了,清屏
            if (lbMessage.Items.Count > 0)
            {
                lbMessage.Items.Clear();
            }
            //else
            //{
            //    MessageBox.Show("没有内容可以被清除");
            //}
        }
        #endregion
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中实现文件传输的断点传功能,需要了解以下几个步骤: 1. 建立连接:使用 TCP 或 UDP 协议建立客户端与服务之间的连接。 2. 发送文件信息:客户端向服务发送文件名、大小、最后修改时间等信息。 3. 接收文件信息:服务接收到文件信息后,根据文件名创建或打开文件,并记录已经传输的字节数。 4. 发送文件数据:客户端将文件数据拆分成多个数据块,每个数据块带上序号,发送给服务。 5. 接收文件数据:服务接收到数据块后,将其写入文件对应的位置,并记录已经接收到的字节数。 6. 检查数据是否完整:客户端和服务都需要检查每个数据块是否已经成功接收,并进行重传或者继传输剩余数据。 7. 断点传:如果传输过程中出现异常,客户端和服务可以记录已经传输的字节数,并在恢复连接后从该位置继传输。 下面是一个简单的 C# 文件传输的断点传示例代码: ```csharp // 客户端代码 TcpClient client = new TcpClient(); client.Connect("127.0.0.1", 8888); NetworkStream stream = client.GetStream(); byte[] fileNameBytes = Encoding.UTF8.GetBytes(fileName); byte[] fileInfoBytes = BitConverter.GetBytes(fileSize); byte[] fileData = File.ReadAllBytes(fileName); stream.Write(fileNameBytes, 0, fileNameBytes.Length); stream.Write(fileInfoBytes, 0, fileInfoBytes.Length); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int bytesSent = 0; int totalBytesSent = 0; while (totalBytesSent < fileSize) { int bytesToSend = Math.Min(bufferSize, fileSize - totalBytesSent); Buffer.BlockCopy(fileData, totalBytesSent, buffer, 0, bytesToSend); stream.Write(buffer, 0, bytesToSend); totalBytesSent += bytesToSend; Console.WriteLine("Sent {0} bytes.", totalBytesSent); } stream.Close(); client.Close(); // 服务端代码 TcpListener server = new TcpListener(IPAddress.Any, 8888); server.Start(); while (true) { TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); byte[] fileNameBytes = new byte[1024]; stream.Read(fileNameBytes, 0, fileNameBytes.Length); string fileName = Encoding.UTF8.GetString(fileNameBytes).Trim('\0'); byte[] fileSizeBytes = new byte[8]; stream.Read(fileSizeBytes, 0, fileSizeBytes.Length); long fileSize = BitConverter.ToInt64(fileSizeBytes, 0); FileStream fileStream = new FileStream(fileName, FileMode.Create); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int bytesReceived = 0; int totalBytesReceived = 0; while (totalBytesReceived < fileSize) { int bytesToReceive = Math.Min(bufferSize, (int)(fileSize - totalBytesReceived)); bytesReceived = stream.Read(buffer, 0, bytesToReceive); fileStream.Write(buffer, 0, bytesReceived); totalBytesReceived += bytesReceived; Console.WriteLine("Received {0} bytes.", totalBytesReceived); } stream.Close(); client.Close(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值