无法将参数传递给控制台应用程序,我的想法是否存在缺陷?
Unable to pass argument to console application, are there flaws in my thinking?
我创建了一个控制台应用程序,它接收示例文本文件并对其进行处理。当我通过 Visual Studio 调试它时,这工作正常,但是当我尝试从命令行 运行 它时,参数没有传递。
我的理解是,我应该能够 运行 通过调用应用程序并传递如下参数:
应用程序参数
在我的情况下会是这样的:
C:\Users\Alex\Desktop\ConsoleApplication2.application C:\Users\Alex\Documents\Sample.txt
有什么明显的我遗漏的东西吗?
但是这样做会产生以下异常:
"Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at ConsoleApplication2.TestProgram.Main(String[] args)"
应通过 C# 代码访问参数,如下所示
public static void Main(string[] args)
{
System.Console.WriteLine(args[0]);
// Read the file as one string.
string text = System.IO.File.ReadAllText(@args[0]);
...
...
rest of method here
...
...
}
如果您从命令提示符 运行 下面的代码应该将第一个参数打印到控制台:
class Program
{
static void Main(string[] args)
{
if(args.Length > 0)
Console.WriteLine(args[0]);
}
}
在 Visual Studio 中构建应用程序。
右键单击解决方案资源管理器中的项目并选择 "Open Folder in File Explorer"
- 浏览到 bin/Debug 或 bin/Release 文件夹或您正在使用的任何构建配置
- 将 .exe 的路径粘贴到命令提示符中,然后 运行 它:
谢谢大家帮我解决这个问题。问题源于我尝试 运行 的文件。当我想从命令提示符 运行 一个 exe 时,我通过 visual studio 发布了一个应用程序。
在这里的第一次体验很棒 ;)
我创建了一个控制台应用程序,它接收示例文本文件并对其进行处理。当我通过 Visual Studio 调试它时,这工作正常,但是当我尝试从命令行 运行 它时,参数没有传递。
我的理解是,我应该能够 运行 通过调用应用程序并传递如下参数:
应用程序参数
在我的情况下会是这样的: C:\Users\Alex\Desktop\ConsoleApplication2.application C:\Users\Alex\Documents\Sample.txt
有什么明显的我遗漏的东西吗?
但是这样做会产生以下异常: "Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at ConsoleApplication2.TestProgram.Main(String[] args)"
应通过 C# 代码访问参数,如下所示
public static void Main(string[] args)
{
System.Console.WriteLine(args[0]);
// Read the file as one string.
string text = System.IO.File.ReadAllText(@args[0]);
...
...
rest of method here
...
...
}
如果您从命令提示符 运行 下面的代码应该将第一个参数打印到控制台:
class Program
{
static void Main(string[] args)
{
if(args.Length > 0)
Console.WriteLine(args[0]);
}
}
在 Visual Studio 中构建应用程序。
右键单击解决方案资源管理器中的项目并选择 "Open Folder in File Explorer"
- 浏览到 bin/Debug 或 bin/Release 文件夹或您正在使用的任何构建配置
- 将 .exe 的路径粘贴到命令提示符中,然后 运行 它:
谢谢大家帮我解决这个问题。问题源于我尝试 运行 的文件。当我想从命令提示符 运行 一个 exe 时,我通过 visual studio 发布了一个应用程序。
在这里的第一次体验很棒 ;)