简体   繁体   English

C# - 确定参数是否已通过的方法失败

[英]C# - Method For Determining If Arguments Have Been Passed Fails

I am creating a Windows Forms Application with c# that can open up a file on startup if it is passed an argument containing the path to the file. 我正在使用c#创建一个Windows窗体应用程序,如果传递包含该文件路径的参数,则可以在启动时打开该文件。

However, it doesn't accurately determine if arguments have been passed. 但是,它无法准确确定参数是否已通过。 Even when I pass no arguments, it still tries to open up a file. 即使我没有传递任何参数,它仍然会尝试打开一个文件。

Here's my code: 这是我的代码:

string[] args = Environment.GetCommandLineArgs();
if (args == null || args.Length == 0)
{

}
else
{
    try
    {
        ListData ld = new LmReader.LmReader().readLmList(args[0]);
        listItemsList.Items.Clear();
        foreach (ListItemList li in ld.lil)
        {
            ListViewItem lvi = new ListViewItem(li.text);
            lvi.Font = li.itemFont;
            listItemsList.Items.Add(lvi);
        }
        filenameOpen = selectOpenLocation.FileName;
        this.Text = "List Maker - " + Path.GetFileNameWithoutExtension(args[0]);
    }
    catch (Exception ex)
    {
        new Error().doError("Your list could not be opened.", ex);
    }
}

What am I doing wrong? 我究竟做错了什么?

Environment.GetCommandLineArgs() always at least returns one argument which is the excecutable file name and then contains the arguments you might have passed in. Environment.GetCommandLineArgs()始终至少返回一个参数,该参数是可加密的文件名,然后包含您可能传入的参数。

So that's why your if condition nether matches 这就是为什么你的if条件与nether匹配

See documentation 文档

From the docs : 来自文档

The first element in the array contains the file name of the executing program 数组中的第一个元素包含正在执行的程序的文件名

Therefore 因此

args.Length == 0

should be 应该

args.Length <= 1

in your case. 在你的情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM