【发布时间】:2016-07-13 21:16:45
【问题描述】:
不知道如何实现这一点,我没有使用 SaveFileDialog,我见过使用 OverWritePrompt = true 似乎无法让它为我工作。
我正在使用 WPF。
结构:-
我有一个名为 filePathBox 的文本框 - 它包含用于打开以下文件的文件路径:OpenFileDialog
private void fileBrowser_Click(object sender, RoutedEventArgs e)
{
//Firstly creating the OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//Setting the filter for the file extension of the files as well as the default extension
dlg.DefaultExt = ".txt";
dlg.Filter = "All Files|*.*";
//Display the dialog box by calling the ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
//Grab the file you selected and display it in filePathBox
if (result == true)
{
//Open The document
string filename = dlg.FileName;
filePathBox.Text = filename;
}
}
然后您可以单击一个按钮,.txt 文件将显示在一个名为 textResult 的文本框中
private void helpfulNotes_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(filePathBox.Text) && System.IO.Path.GetExtension(filePathBox.Text).ToLower() == ".txt")
{
textResult.Text = File.ReadAllText(filePathBox.Text);
}
if (string.IsNullOrWhiteSpace(filePathBox.Text))
{
MessageBox.Show("Please choose a file by clicking on the folder Icon :(");
}
}
一旦您对“textResult”中的文本进行了更改,我就有一个按钮可以将文本保存回最初使用 OpenFileDialog 加载的文件路径
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
目前一切正常,只是没有提示用户说你确定要覆盖文件。
现在可以
- 为此目的将一个名为 TestNote.txt 的文件加载到 文件路径框
- 在 textResult 中键入一些文本,甚至在单击以显示 文件
- 点击保存,它只会用文本 i 覆盖 TestNote.txt 刚刚进入,甚至没有警告我
希望我已经充分解释了这一点并提供了您需要的所有代码
【问题讨论】:
-
你已经完成了所有这些,“显示对话框要求用户确认他们希望继续”的哪一部分你还在坚持?
-
为什么不在
Microsoft.Win32命名空间中使用SaveFileDialog?
标签: c#