打开文件并加载它
本文关键字:加载 文件 | 更新日期: 2023-09-27 18:12:28
我正在创建一个使用特定文件类型的程序,并且我已经将该文件类型与程序相关联,但是当我单击该文件时,它只启动程序,但它不加载我单击的文件。我怎样才能使我的程序加载文件?
当您打开与应用程序相关联的文件时,文件路径将作为命令行参数传递到程序中。你可以自己加载文件,像这样:
string fileName = Environment.GetCommandLineArgs()[0];
在你的应用程序中,你必须使用Main(string[] args)
并从args中获取参数传递给你的应用程序。
下面是一个例子:
static void Main(string[] args)
{
if (args.Length == 0) return;
string text = File.ReadAllText(args[0]);
}
您可以使用static void Main(string[] args)
来获取文件名。
我会这样做:
在你的代码的某个地方,你应该有一个字符串变量存储检索到的文件名private string filename;
static void Main(string[] args) {
// first check if there are arguments
if (args.length > 0)
{
// check if the filename has the right extension
if (args[0].EndsWith(".ext"))
{
// check for existence
if (System.IO.File.Exists(args[0]))
{
// it exists.. so store the filename in the previously defined variable
filename = args[0];
}
}
}
}
这样,当文件名变量有内容时,您可以执行一种逻辑,而当它没有内容时,您可以执行另一种逻辑。