2013-07-12 35 views
0

我需要創建x個文件(一組),但我必須首先檢查文件是否存在具有相似名稱的文件。如果上一組文件存在,自動增加文件名結尾

例如,tiftest1.tif,tiftest2.tif,...存在,我必須再次將tiftest寫入相同的目錄。我希望將_x附加到文件名的末尾,其中x是一個自動遞增的數字,每當我想創建該集時。所以我可以有tiftest1_1.tif,tiftest2_1.tif,tiftest1_2.tif,tiftest2_2.tif,tiftest1_3.tif,tiftest2_3.tif等等。

這是我到目前爲止有:

... 
DirectoryInfo root = new DirectoryInfo(fileWatch.Path); 
FileInfo[] exist = root.GetFiles(fout + "*.tif"); 

if (exist.Length > 0) 
{ 
    int cnt = 0; 
    do 
    { 
     cnt++; 
    DirectoryInfo root1 = new DirectoryInfo(fileWatch.Path); 
     FileInfo[] exist1 = root.GetFiles(fout + "*" + "_" + cnt + ".tif"); 

     arg_proc = "-o " + "\"" + fileWatch.Path 
     + "\\" + fout + "%03d_" + cnt + ".tif\" -r " + "\"" + openDialog.FileName + "\""; 

    } while (exist1.Length > 0); //exist1 is out of scope so this doesn't work 
} 
else 
{ 

    arg_proc = "-o " + "\"" + fileWatch.Path 
     + "\\" + fout + "%03d.tif\" -r " + "\"" + openDialog.FileName + "\""; 
} 
... 

exist1.length超出範圍,所以,循環將持續運行。我不確定如何解決這個問題。我的方法是最初掃描匹配目錄並查看數組的長度是否大於0.如果它大於0,則_x將自動增加,直到找不到匹配。 arg_proc是一個在函數中使用的字符串(不包括),它將創建文件。

回答

0

難道你不能重用你的exist變量嗎?

FileInfo[] exist = root.GetFiles(fout + "*.tif"); 

if (exist.Length > 0) 
{ 
    int cnt = 0; 
    do 
    { 
     cnt++; 
     DirectoryInfo root1 = new DirectoryInfo(fileWatch.Path); 
     exist = root.GetFiles(fout + "*" + "_" + cnt + ".tif"); 

     arg_proc = "-o " + "\"" + fileWatch.Path + "\\" 
     + fout + "%03d_" + cnt + ".tif\" -r " + "\"" + openDialog.FileName + "\""; 

    } while (exist.Length > 0); 
} 
... 

這樣,exist不會超出範圍。當你開始增加你的計數器時,它看起來並不像你需要原始文件列表,所以如果是這樣的話,你可以繼續使用exist來計算你現有的文件名。

相關問題