Windows 窗体 RichTextBox 控件可以下几种格式之一编写其所显示的信息:
纯文本
Unicode 纯文本
富文本格式 (RTF)
用空格代替 OLE 对象的 RTF
具有 OLE 对象的文本表示形式的纯文本
若要保存文件,请调用 SaveFile 方法。 还可以使用 SaveFile 方法将数据保存到流。 有关详细信息,请参阅 SaveFile(Stream, RichTextBoxStreamType)。
将控件的内容保存到文件
确定要保存的文件的路径。
若要在实际应用程序中执行此操作,通常使用 SaveFileDialog 组件。 有关概述,请参阅 SaveFileDialog 组件概述。
调用 SaveFile 控件的 RichTextBox 方法,指定要保存的文件和可选的文件类型。 如果使用文件名作为唯一参数调用该方法,该文件将另存为 RTF。 若要指定另一个文件类型,请使用 RichTextBoxStreamType 枚举的值作为第二个参数调用该方法。
在下面的示例中,为富文本文件的位置设置的路径是 我的文档 文件夹。 之所以使用此位置,是因为你可以假定运行 Windows 操作系统的大多数计算机将包含此文件夹。 选择此位置还允许用户使用最少的系统访问级别安全地运行应用程序。 以下示例假定窗体已添加控件 RichTextBox。
Public Sub SaveFile() ' You should replace the bold file name in the ' sample below with a file name of your own choosing. RichTextBox1.SaveFile(System.Environment.GetFolderPath _ (System.Environment.SpecialFolder.Personal) _ & "\Testdoc.rtf", _ RichTextBoxStreamType.RichNoOleObjs) End Sub
public void SaveFile() { // You should replace the bold file name in the // sample below with a file name of your own choosing. // Note the escape character used (@) when specifying the path. richTextBox1.SaveFile(System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal) + @"\Testdoc.rtf", RichTextBoxStreamType.RichNoOleObjs); }
public: void SaveFile() { // You should replace the bold file name in the // sample below with a file name of your own choosing. richTextBox1->SaveFile(String::Concat (System::Environment::GetFolderPath (System::Environment::SpecialFolder::Personal), "\\Testdoc.rtf"), RichTextBoxStreamType::RichNoOleObjs); }
重要
如果该文件尚不存在,则此示例将创建一个新文件。 如果应用程序需要创建文件,该应用程序需要创建文件夹的访问权限。 权限是使用访问控制列表设置的。 如果文件已存在,则应用程序仅需要写访问权限,所需权限较低。 如果可能,在部署期间创建文件更安全,并且只授予对单个文件的读取访问权限,而不是为文件夹创建访问权限。 此外,将数据写入用户文件夹比根文件夹或 Program Files 文件夹更安全。