使用命令args

时间:2016-07-28 18:46:55

标签: c# winforms command-line-arguments filepath

我目前正在编写一个文本编辑器程序,但是我遇到了一个问题。

我试图让用户通过双击程序打开我的程序文件,这可以通过设置默认程序来实现。我被告知这会将程序作为命令参数发送给程序。 我这样使用它:

    private void formMain_Load(object sender, EventArgs e)
    {
        string[] args = System.Environment.GetCommandLineArgs();
        string filePath = args[1];
        addTab();
        getFontCollection();
        setFontSizes();
        getCurrentDocument.Text = (File.ReadAllText(filePath));

    }

但是,我一直收到以下错误:

An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll

Additional information: The given path's format is not supported.

如果有人愿意指示我解决这个问题,我们将不胜感激。 顺便说一句,整个源代码位于Github,github.com / Criticaldiamonds / asys

修改

根据MSDN,第一个参数是程序本身,后跟用户指定的参数。因此,

args[0] = the program
args[1] = "C:\users\Giovanni\Desktop\Hello.txt" (w/o quotes ofc)

由于VS调试器会转义字符,因此调试器中的args[1] 的值为“C:\\ users \\ Giovanni \\ Desktop \\ Hello.txt”

2 个答案:

答案 0 :(得分:1)

您应该使用System.IO.Path

上的方法
private void Form1_Load(object sender, EventArgs e)
{
    var args = System.Environment.GetCommandLineArgs();
    // using linq here reduces that array count check then extract
    var argPath = args.Skip(1).FirstOrDefault();
    if (!string.IsNullOrEmpty(argPath))
    {
        // Your .LoadFile(...) method requires a full path
        var fullPath = Path.GetFullPath(argPath);
        /* this part isn't needed unless you want to ensure the directory exists... but if it doesn't exist you can't open it anyway
        var dirPath = Path.GetDirectoryName(fullPath);
        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);
        */
        /* this isn't needed since you are using the full path
        Directory.SetCurrentDirectory(dirPath);
        */ 
        addTab();
        getFontCollection();
        setFontSizes();
        getCurrentDocument.LoadFile(fullPath, RichTextBoxStreamType.PlainText);
    }
}

答案 1 :(得分:0)

我设法解决了这个问题!感谢所有留下评论的人,他们真的很有帮助! 通过搞乱目录设置,我最终得到了以下代码,它正确加载了测试文件!

private void formMain_Load(object sender, EventArgs e)
{
    string[] args = System.Environment.GetCommandLineArgs();
    string dirPath = args[1];
    string fileName = "";
    fileName = Path.GetFileName(dirPath);
    dirPath = dirPath.Substring(3);
    dirPath = Path.GetFullPath(dirPath);
    if (dirPath.Contains('\\')) dirPath = dirPath.Substring(0, dirPath.LastIndexOf('\\'));
    Directory.SetCurrentDirectory(dirPath);
    addTab();
    getFontCollection();
    setFontSizes();
    getCurrentDocument.LoadFile(dirPath + '\\' + fileName, RichTextBoxStreamType.PlainText);
}