[英]How to open a text file in C#/WinForms/TextBox - mad Editor
我在WinForms中开发了一个文本编辑器。 你可以从这里下载并使用它。 它工作正常。 但是,当我在Windows资源管理器中右键单击文本文件并尝试打开它时,它不会显示它。 我在网上搜索了解决方案,但失败了。 你能建议解决这个问题。 或者我应该使用RichTextBox。 我还尝试使用RichTextBox
创建一个简单的Test项目并使用LoadFile()
。
// Load the contents of the file into the RichTextBox.
richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);
这导致文件格式错误。
问题是使用:
richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);
您必须选择RTF格式(RTF)文件,因为加载普通文本文件会导致文件格式错误(ArgumentException)。 所以你可以用这种方式加载它:
string[] lines = System.IO.File.ReadAllLines(openFile1.FileName);
richTextBox1.Lines = lines;
好的,根据您的评论和提供的代码,它将无法从Windows打开文件。
当Windows将文件发送到程序以打开它时,它会将其作为第一个参数发送给exe,例如notepad.exe C:\\Users\\Sean\\Desktop\\FileToOpen.txt
。
您需要使用Environment.CommandLine
或Environment.GetCommandLineArgs()
来获取参数。
有关详细信息,请参阅此处: 如何将命令行参数传递给WinForms应用程序?
我会在你的表单的Load
事件中处理这个并将参数传递给你的函数:
string filename = Environment.GetCommandLineArgs()[0];
richTextBox1.LoadFile(filename, RichTextBoxStreamType.RichText);
我刚刚解决了这个问题。 谢谢你的帮助。
我正在为面临类似问题的未来帮助添加答案。
这是解决方案:
从Form_Load()调用以下方法:
public void LoadFileFromExplorer()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
string filename1 = Environment.GetCommandLineArgs()[1];
richTextBox1.LoadFile(filename1, RichTextBoxStreamType.PlainText);
}
}
要使其工作,请更改Main():
static void Main(String[] args)
{
if (args.Length > 0)
{
// run as windows app
Application.EnableVisualStyles();
Application.Run(new Form1());
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.