注册 登录
编程论坛 C# 论坛

c#程式写好,exe文件挂在任务计划程序下,过段时间exe文件会变大并运行报错,应该是哪里资源没释放,但没找到,求高手帮忙看下

shl615807585 发布于 2021-11-23 12:04, 1663 次点击
//批量处理文件,把目标文件夹srcPath下的文件更名并移动到指定文件夹destPath下
static void Main(string[] args)
        {
            string[] srcPath = new string[] { @"D:\CR80", @"D:\CR81", @"D:\CR82" };
            string destPath = @"D:\CRMAPdata";
            CRmove cr = new CRmove();
            for (int i = 0; i < 3; i++)
            {
                cr.MOVE(srcPath[i], destPath);
            }
        }
class CRmove
    {
        private string[] data = new string[10];
        private string[] time = new string[20];
        private string Newtime = "";
        private string newPath = "";
        public void MOVE(string srcPath,string destPath)
        {
            foreach (string file in Directory.GetFiles(srcPath, "*.FXY", SearchOption.AllDirectories))
            {
                try
                {
                    //读取文件第一行
                    //1.创建StreamReader对象,并指定要读取的文件,与编码格式
                    StreamReader sr = new StreamReader(file, Encoding.UTF8);
                    //2.调用StreamReader对象的readline方法,读取第1行
                    string content = sr.ReadLine();
                    //根据空格分隔第一行数据,取data[3]加上文件创建时间作为新文件名
                    data = content.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    sr.Dispose();
                        Fileinfo fi = new FileInfo(file);
                        //取文件时间
                        time = fi.LastWriteTime.ToString().Split(new char[] { ' ', '/', ':' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < time.Length; i++)
                        {
                            Newtime += time[i];
                        }
                        //新文件路径
                        newPath = destPath + @"\" + data[3] + @"-" + Newtime + @".FXY";
                        Newtime = "";
                        if (!Directory.Exists(newPath))
                        {
                            //将新命名文件移到新文件夹
                            fi.MoveTo(newPath);
                            Console.WriteLine(file + "修改完成");
                        }
                }
                catch (Exception)
                {
                    Console.WriteLine(srcPath + @"\" + file + "修改失败");
                    //Console.ReadKey();
                }
            }
        }
    }
1 回复
#2
月夜枫华2022-02-21 10:10
1-sr流在使用后应先close
2- if (!Directory.Exists(newPath))
                        {
                            //将新命名文件移到新文件夹
                            fi.MoveTo(newPath);
                            Console.WriteLine(file + "修改完成");
                        }
你判断了目标文件夹不存在,但应先创建目标文件夹,然后再移动文件。
1