JohnChris JohnChris - 9 days ago 6
C# Question

Exporting a .txt, no overwrite warning appears

When executing the following code, I would expect a warning pop up dialog, which will ask if I am sure I would like to overwrite the file, but no pop up appears. Does anyone know a simple way to implement it? Without having to create my own custom window

XAML:

<Grid>
<TextBox x:Name="name" Text="hi" />
<Button x:Name="create_File" Click="create_File_Click" Content="make the notepad" Width="auto"/>
</Grid>


c#:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

public void createFile()
{

string text_line = string.Empty;
string exportfile_name = "C:\\" + name.Text + ".txt";

System.IO.StreamWriter objExport;
objExport = new System.IO.StreamWriter(exportfile_name);

string[] TestLines = new string[2];
TestLines[0] = "****TEST*****";
TestLines[1] = "successful";


for (int i = 0; i < 2; i++)
{
text_line = text_line + TestLines[i] + "\r\n";
objExport.WriteLine(TestLines[i]);

}
objExport.Close();
MessageBox.Show("Wrote File");

}
private void create_File_Click(object sender, RoutedEventArgs e)
{
createFile();
}
}


UPDATE

I was not using SaveFileDialog, Now I am and it works just how I would expect it too... thanks for the answers, here is what I have now:

public void createFile()
{
string text_line = string.Empty;
string export_filename = name.Text;


Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = export_filename; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();


// save file
System.IO.StreamWriter objExport;
objExport = new System.IO.StreamWriter(dlg.FileName);

string[] TestLines = new string[2];
TestLines[0] = "****TEST*****";
TestLines[1] = "successful";



for (int i = 0; i < 2; i++)
{
text_line = text_line + TestLines[i] + "\r\n";
objExport.WriteLine(TestLines[i]);

}
objExport.Close();


}


private void create_File_Click(object sender, RoutedEventArgs e)
{
createFile();
}

}

Answer

Asking the user whether the file should be overwritten is usually done when the file path is chosen, not when the file is actually written.

If you let the user choose the path using a SaveFileDialog, the OverwritePrompt property is set to true by default, resulting in the confirmation dialog you desire.

If you don't want to use the SaveFileDialog, you can use a MessageBox with the MessageBoxButtons.YesNo option.

Comments