执行以下代码时,我会发出一个警告弹出对话框,询问我是否确定要覆盖该文件,但不会弹出窗口。有谁知道一种简单的方法来实现它?无需创建自己的自定义窗口
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();
}
}
更新
我没有使用SaveFileDialog,现在我就是这样,我的期望也是如此...感谢答案,这就是我现在所拥有的:
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();
}
}
答案 0 :(得分:2)
询问用户是否应覆盖该文件通常是在选择文件路径时完成,而不是在实际写入文件时。
如果您允许用户使用SaveFileDialog选择路径,则OverwritePrompt property默认设置为true
,从而生成您想要的确认对话框。
如果您不想使用SaveFileDialog,则可以MessageBox
使用MessageBoxButtons.YesNo option。
答案 1 :(得分:2)
答案 2 :(得分:1)
DialogResult dialogResult = File.Exists(exportfile_name)
? MessageBox.Show(null, "Sure?", "Some Title", MessageBoxButtons.YesNo)
: DialogResult.Yes;
if (dialogResult == DialogResult.Yes)
{
// save file
}