2016-11-25 70 views
-2

当执行下面的代码时,我希望弹出一个警告对话框,它会询问我是否确定要覆盖文件,但是没有弹出窗口。有谁知道一个简单的方法来实现它?无需创建自己的自定义窗口导出一个.txt文件,不会出现覆盖警告

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我没有使用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(); 
    } 

} 
+1

为什么你会希望出现一个确认对话框休息吗?你需要自己处理这个逻辑......另外,你需要将你的流包装在一个“使用”块中 – musefan

+0

你为什么期望?您正在使用'StreamWriter'直接写入文件,这只是一个类而不是UI元素。 'SaveFileDialog'将在选择现有文件时要求确认,但对于'StreamWriter',这根本没有任何意义(否则没有UI的应用程序永远不能使用'StreamWriter')。 – bassfader

+0

@ 2以上,嗯好吧好吧谢谢你的答案 – JohnChris

回答

2

1)检查文件是否存在(File.Exists

2)如果是的话,显示有是一个MessageBox(MessageBox.Show),并没有选项。

3)检查,如果用户点击是,然后才执行代码的

+0

@感谢给我一种方法来做到这一点,我用的方法,但SaveFileDialog更有意义,只是没有' t知道它 – JohnChris

1
DialogResult dialogResult = File.Exists(exportfile_name) 
    ? MessageBox.Show(null, "Sure?", "Some Title", MessageBoxButtons.YesNo) 
    : DialogResult.Yes; 

if (dialogResult == DialogResult.Yes) 
{ 
    // save file 
} 
+0

这是美丽的,谢谢另一种方式来做到这一点! – JohnChris