iT邦幫忙

1

C# 遷移資料夾裡的檔案到另一個資料夾

c#
Pyan 2019-11-28 10:21:461506 瀏覽

我在date資料夾裡面有AAA和BBB資料夾
我想把AAA資料夾裡的文字檔做些更改後
產稱新的TXT到BBB資料夾

不過我下面的做法很明顯就是只能指定a.txt更改後產生b.txt

如果我想要一次把所有在AAA裡面的txt都做更改
然後在BBB產生出來
請教各位大大我該如何處理

 static void Main(string[] args)
    {
   string rootPath = "D:\\date\\";
   string aName, bName, aFilePath, bFilePath;
   
     aName = "a.txt";
     bName = "b.txt";
     aFilePath = $"{rootPath}AAA\\{aName}";
     bFilePath = $"{rootPath}BBB\\{bName}";
     
    class1.Encrypt(aFilePath,bFilePath);
    }
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
sion
iT邦新手 4 級 ‧ 2019-11-28 10:32:15
最佳解答

System.IO裡面有個東西叫做 Directory
檔案操作除了File類別外,還有Directory、Path、Stream等類別要熟悉

var allfile = Directory.GetFiles("C:\\Users\\Desktop");
foreach(string file in allfile)
{
    ...
}
3
海綿寶寶
iT邦大神 1 級 ‧ 2019-11-28 10:39:48
String directoryName = "C:\\Consolidated";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
    Directory.CreateDirectory(directoryName);

List<String> MyMusicFiles = Directory
                   .GetFiles("C:\\Music", "*.*", SearchOption.AllDirectories).ToList();

foreach (string file in MyMusicFiles)
{
    FileInfo mFile = new FileInfo(file);
    // to remove name collisions
    if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false) 
    {
         mFile.MoveTo(dirInfo + "\\" + mFile.Name);
    }
}

參考資料來源

如果是要copy而不是move
那就把 MoveTo 改成 CopyTo 即可

選我正解

我要發表回答

立即登入回答