欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# copy files from source directory to destination file and rename repeated files and does not override

程序员文章站 2022-07-17 08:43:29
static void CopyFiles() { string sourceDir = @"D:\C\ll"; string destDir = @"D:\LL"; if (!Directory.Exists(destDir)) { Directo... ......
  static void copyfiles()
        {
            string sourcedir = @"d:\c\ll";
            string destdir = @"d:\ll";
            if (!directory.exists(destdir))
            {
                directory.createdirectory(destdir);
            }

           string[] mp3files= directory.getfiles(sourcedir, "*.mp3", searchoption.alldirectories);
           if(mp3files!=null && mp3files.any())
            {
                dictionary<string, string> dic = new dictionary<string, string>();
                list<string> repeatedlist = new list<string>();
                foreach (string mp3 in mp3files)
                {                  
                    string mp3filename = path.getfilename(mp3);
                    string newmp3filename = path.getfilename(mp3);
                    if (dic.containskey(mp3filename))
                    {                         
                        string guid = guid.newguid().tostring().substring(0, 6);
                        newmp3filename = path.getfilenamewithoutextension(mp3filename) + guid + ".mp3";
                        dic.add(newmp3filename, newmp3filename);
                        string repeatedmsg = $"mp3:{mp3},newmp3filename:{newmp3filename}";
                        repeatedlist.add(repeatedmsg);
                    }
                    else
                    {
                        dic.add(mp3filename, mp3filename);
                    }

                    string newmp3fullname = path.combine(destdir, newmp3filename);
                    file.copy(mp3, newmp3fullname, false);
                    console.writeline($"oldmp3:{mp3},newmp3fullname:{newmp3fullname}");
                }
                dic = null;

                console.writeline($"\n\n there are {repeatedlist.count} repeated msg:");
                repeatedlist.foreach(x =>
                {
                    console.writeline(x);
                });
            }           
        }