2016-07-26 108 views
-2

我尝试打开一个文本文档,然后收到消息:try-catch中的无效文件格式。我使用Visual Studio 2015与Visual C#和Windows窗体应用程序。为什么我的OpenFileDialog没有工作?

这里我对开放的功能代码:

private void openToolStripMenuItem_Click(object sender, EventArgs e) 
{ 
    try { 
    // Create an OpenFileDialog to request a file to open. 
    OpenFileDialog openFile1 = new OpenFileDialog(); 

    // Initialize the OpenFileDialog to look for RTF files. 

    openFile1.Filter = "Text Files (*.txt)|*.txt| RTF Files (*.rtf)|*.rtf| All (*.*)|*.*"; 

    // Determine whether the user selected a file from the OpenFileDialog. 
    if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK && 
     openFile1.FileName.Length > 0) 
    { 
     // Load the contents of the file into the RichTextBox. 
     TextBox.LoadFile(openFile1.FileName); 
    } 
    } 
    catch (Exception a) 
    { 
     MessageBox.Show(a.Message); 
    } 
}//end open 

我希望你能帮助我与友好的愿望sniffi。

+0

什么是完整的文件路径和名称要载入? –

+0

C:\ Users \ H179850 \ Documents \ Verschiedene Aufzeichnungen(< - 表示不同的记录) – sniffi

+0

它是.txt还是.rtf?因为如果没有,那么你将无法加载它 –

回答

2

问题可能是您不加载RTF文档 - 请参阅MSDN上的docs

使用此版本的的LoadFile方法,如果正在加载的文件是 不RTF文档,一个异常将发生。加载文件的不同类型 如ASCII文本文件,使用方法其他版本的接受一个从RichTextBoxStreamType枚举 作为参数值。

因此尝试使用这种方法,它接受流类型等的重载version左右(按需要调整)

TextBox.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText); 
+0

我得到了同样的错误信息给我一分钟我必须阅读从RichTextBox.LoadFile方法(字符串,RichTextBoxStreamType)的msdn帮助 – sniffi

+0

Sry,但我不认为我需要,因为我想打开多种类的流。我必须打开例如.txt和.dau数据。 – sniffi

+0

那么您必须事先知道要打开哪种类型的流,然后使用适当的流类型。如果你不知道一些扩展名(我们称之为.dummy)是纯文本还是RTF等,系统应该如何知道如何处理它? – DAXaholic