2009-06-02 50 views
0

,當我們創建一個與現有文件具有相同名稱的新文件時,不會提示用戶輸出文件已存在的消息,但它創建了(1)在文件名末尾...在windows環境和幾個應用程序中創建'新文件Windows'行爲

name.doc 

name(1).doc 

我試圖創建在C#中相同的行爲一個新的文件,我的問題是, ...我可以減少所有這些代碼嗎?

FileInfo finfo = new FileInfo(fullOutputPath); 
if (finfo.Exists) 
{ 
    int iFile = 0; 
    bool exitCreatingFile = false; 
    while (!exitCreatingFile) 
    { 
    iFile++; 
    if (fullOutputPath.Contains("(" + (iFile - 1) + ").")) 
     fullOutputPath = fullOutputPath.Replace(
       "(" + (iFile - 1) + ").", 
       "(" + iFile + ")."); // (1) --> (2) 

    else 
     fullOutputPath = fullOutputPath.Replace(
       Path.GetFileNameWithoutExtension(finfo.Name), 
       Path.GetFileNameWithoutExtension(finfo.Name) + "(" + iFile + ")"); // name.doc --> name(1).doc 

    finfo = new FileInfo(fullOutputPath); 
    if (!finfo.Exists) 
     exitCreatingFile = true; 
    } 
} 

回答

2

如何(不添加任何進一步的異常周圍的FileInfo的構造處理):

FileInfo finfo = new FileInfo(fullOutputPath); 
int iFile = 1; 
while (finfo.Exists) 
{ 
    finfo = new FileInfo(
     Path.GetFileNameWithoutExtension(fullOutputPath) + 
     "(" + iFile + ")" + 
     Path.GetExtension(fullOutputPath)); 
    iFile++; 
} 
// Optionally add fullOutputPath = finfo.Name; if you want to record the final name used 
+0

多清潔:)謝謝 – balexandre 2009-06-02 12:00:35

2

我寫了一個Winforms控件來處理文件菜單實現的大部分細節。我認爲它不會使用更少的代碼(儘管實現方式不同),但您可能需要查看一下。

FileSelect控制

+0

thxs,我的WinForms開發時都會有一點! – balexandre 2009-06-02 12:00:16

相關問題