我正在编程,在微软的Visual Studio 2015中,使用c#。
我正试图使一个Windows窗体应用程序,将用于打开简单的。txt,或其他类型的文件,并编辑它们。
但重点是我想打开我的程序:右键单击。txt文件->打开->我的程序。
我的问题是,我应该怎么做,如果我只有我的程序的解决方案文件?当我的程序已经运行时,我真的不在乎打开。txt文件。我希望能够启动它,就像我之前提到的。
我使用这个程序作为一个起点,从哪里下次我将能够使一个简单的mp3播放器,或这样的。据我所知,人们通常不会先打开mp3播放器程序,然后再打开他们想要播放的mp3播放器文件。我希望这能对我努力完成的目标有所启发。
我一直在寻找解决办法,但我找不到。也许这真的很容易,但对我来说,目前还不是。谢谢你的帮助。
My Program.cs是这样的:
static void Main(string[] args)
{
//with args(user open file with the program)
if(args != null && args.Length > 0)
{
string fileName = args[0];
//check file exists
if (File.Exists(fileName))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MainForm = new Form1();
MainForm.OpenFile(fileName);
Application.Run(MainForm);
}
//the file does not exist
else
{
MessageBox.Show("The file does not exist!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
//without args
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
如果您在询问如何处理打开文件,请尝试以下操作:
在Form1.cs中,通过添加另一个定义重载构造函数。
public Form1(string fileName)
{
InitializeComponent();
openFileNow(fileName);
}
-创建openFileNow方法(异步)
private async void openFileNow(string fileName)
{
try
{
if(fileName.EndsWith(".txt"))
{
//Obviously you'll do something different with an .mp3
using (StreamReader reader = new StreamReader(fileName))
{
txtEditBox.Text = await reader.ReadToEndAsync();
}
}
else
{
MessageBox.Show("Can't open that file.");
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
-将Program.cs编辑为:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MainForm;
if (args != null && args.Length > 0)
{
MainForm = new Form1(args[0]);
}
else
{
MainForm = new Form1();
}
Application.Run(MainForm);
}
在Visual Studio中,在项目的属性下,您可以在"Debug"部分添加命令行参数。
如果您想将文件扩展名与应用程序关联,您可以在注册表中这样做。你可以用c#来做,但是ClickOnce的设置会干净得多。
打开项目属性-> Publish -> Options -> fileasassociations
编辑-注意,如果你打算用ClickOnce发布,你需要修改Program.cs中的几行:
string fileName = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
if (fileName != null && fileName.Length > 0)
{
MainForm = new Form1(fileName);
}
如果您只是在寻找与文件关联的调试,请尝试右键单击.txt文件,打开…(更多选项)并从项目的调试文件夹导航到.exe,即:
C: MyProject MyProject bin VS项目调试 myProgram.exe
显然这是一个临时解决方案。享受吧!
在您的表单中添加一个button1(或根据您的需要更改它)并添加以下逻辑:
无论打开什么文件,下面的逻辑都将使用系统默认程序打开它们,而无需进一步询问。
BTW, Form1没有OpenFile方法,你可能从某个地方得到了它。您可以删除它或添加方法定义。
<罢工> MainForm.OpenFile(文件名);罢工 罢工>
private void button1_Click(object sender, EventArgs e)
{
var fileDialog1 = new OpenFileDialog
{
InitialDirectory = "c:\",
RestoreDirectory = true
};
if (fileDialog1.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Process.Start(fileDialog1.FileName);
}
}
如果这不是你想做的,那么你可能不得不写注册表进行文件关联。我在上面的评论中给出了链接