我该如何在 C# 中打开一个文件?我的意思不是使用 TextReader 和 ReadLine() 读取它,而是像在记事本中一样单独打开它。
System.Diagnostics.Process.Start()
。Process.Start("notepad.exe", fileName);
更通用的方法:
Process.Start(fileName);
第二种方法可能是更好的实践,因为这将导致Windows Shell使用其关联的编辑器打开您的文件。此外,如果指定的文件没有关联,它将从Windows使用“打开方式...”对话框。
注意:感谢评论区的意见。我的快速回答有些不对,我已经更新了答案以反映正确的方法。
Process.Start(filename)
存在潜在的命令注入风险,攻击者可以将 MyTextFile.txt
替换成 MyMalicious.bat
或 fdisk ...
。更好的方式是使用 Process.Start("notepad.exe", filename)
。 - Geoff Bennett你提供的信息不够丰富,但是假设你想要用指定文件类型默认处理程序打开计算机上的任意文件, 你可以使用类似于以下代码:
var fileToOpen = "SomeFilePathHere";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};
process.Start();
process.WaitForExit();
使用 UseShellExecute 参数可以告诉 Windows 使用打开该文件类型的默认程序。
WaitForExit 会导致你的应用程序等待所启动的应用程序关闭后才继续执行。
if(File.Exists(fileToOpen))
。 - Wiccio这将使用默认的 Windows 程序打开文件(如果您没有更改它,则为记事本);
Process.Start(@"c:\myfile.txt")
System.Diagnostics.Process.Start( "notepad.exe", "text.txt");
您可以使用Process.Start
,将文件作为参数调用notepad.exe
。
Process.Start(@"notepad.exe", pathToFile);
Process.Start(@“%windir%\notepad.exe”);
会抛出Win32Exception:“找不到文件”,但通常应该可以工作。 - Aren
Process.Start
没有自动扩展 "%windir%",但是像 viabhav 的回答 中省略它或显式扩展它 (Environment.GetEnvironmentVariable("windir")
) 都可以成功地工作。 - Brian