【发布时间】:2017-04-09 20:56:52
【问题描述】:
当执行以下代码时,我希望会弹出一个警告对话框,询问我是否确定要覆盖文件,但没有弹出窗口出现。有谁知道实现它的简单方法?无需创建自己的自定义窗口
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();
}
}
【问题讨论】:
-
为什么会出现确认对话框?您需要自己处理该逻辑...此外,您需要将流包装在
using块中 -
为什么会这样?您正在使用
StreamWriter直接写入文件,这只是一个类而不是 UI 元素。SaveFileDialog会在选择现有文件时要求确认,但对于StreamWriter,这根本没有意义(否则没有 UI 的应用程序永远无法使用StreamWriter)。 -
@2 以上,嗯好的,谢谢你的回答