2017-02-14 145 views
0

如何在寫入正在由其他程序使用的文件時保持savefilediallog處於打開狀態,以便可以更改文件名並嘗試再次保存?Savefiledialog鎖定文件,更改文件名

private void button1_Click_2(object sender, EventArgs e) 
{ 
    Cursor.Current = Cursors.WaitCursor; 
    CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken); 
    Cursor.Current = Cursors.Default; 

    saveFileDialog1.OverwritePrompt = true; 

    saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*"; 
    saveFileDialog1.DefaultExt = "csv"; 
    saveFileDialog1.AddExtension = true; 
    saveFileDialog1.ShowDialog(); 
} 

private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) 
{ 
    try 
    { 
     string name = saveFileDialog1.FileName; // Get file name.   
     File.WriteAllText(name, CsvExport);  // Write to the file name selected. 
    } 
    catch (Exception ex) 
    { 
     //file is locked, how to get back to the open save file dialog ??? 
    } 
} 
+0

也許[this](http://stackoverflow.com/questions/3846646/exception-in-opening-a-file-that-is-already-open)可以幫助你。 –

+0

你不應該那樣做。你可以把你的用戶放在一個循環中,唯一的出路是取消或選擇一個不同的名字,並且在不產生大量鼠標點擊的情況下提醒他們有效地提醒他們可能會變得相當麻煩...... –

+2

已建立的UX模式將首先向用戶提供反饋,該文件被鎖定以便寫入(理想情況下:由誰/哪個進程)。該消息將提供取消或重試的選項,重試時您將再次打開savefiledialog。如果您重複使用相同的實例,它將保留上次選擇的路徑和文件名,以免對用戶造成麻煩。 – dlatikay

回答

1

試試這個。從button1_Click移動與開saveFileDialog1到它自己的功能相關的代碼,並調用該函數:

private void button1_Click_2(object sender, EventArgs e) 
{ 
    Cursor.Current = Cursors.WaitCursor; 
    CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken); 
    Cursor.Current = Cursors.Default; 

    ShowSaveFileDialog(); 
} 

private void ShowSaveFileDialog() 
{ 
    saveFileDialog1.OverwritePrompt = true; 

    saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*"; 
    saveFileDialog1.DefaultExt = "csv"; 
    saveFileDialog1.AddExtension = true; 
    saveFileDialog1.ShowDialog(); 
} 

編輯:在進一步的考慮,我不認爲你想/需要這裏的循環,所以我刪除它。你還是想在這裏調用ShowSaveFileDialog方法在異常情況下,雖然:

private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) 
{ 
    try 
    { 
     string name = saveFileDialog1.FileName; // Get file name.   
     File.WriteAllText(name, CsvExport);  // Write to the file name selected. 
     return; 
    } 
    catch (Exception ex) 
    { 
     //file is locked, how to get back to the open save file dialog ??? 
     // maybe display an error message here so that the user knows why they're about to see the dialog again. 
    } 
    ShowSaveFileDialog(); 
} 

從技術上講,如果用戶試圖重複這大概可以導致StackOverflowException(我的意思是上千次),重試後保存一個例外,但這不太可能。