[英]how to pass parameters for opening files C#
我對c#很新,我在嘗試理解這個問題時遇到了問題。 如何將參數傳遞給(或從我傾向於混淆術語)主函數以便讀取文本文件? 我有一個python函數,可以更好地顯示我想要做的事情。
def readFile(filename):
data = []
source = file(filename)
for line in source:
words = line.split()
for word in words:
data.append(int(word))
source.close()
return data
我對如何在c#中打開文件有一個基本的了解,但是在網上搜索我找不到任何可以幫助我做我想要的或者至少幫助翻譯的東西。 這是我的基本理解:
using System;
using System.Text;
using System.IO;
public class Readingfiles {
public static void Main()
{
StreamReader src = new StreamReader("Data.txt");
while(!src.EndOfStream)
{
string line = src.ReadLine();
Console.WriteLine(line);
}
}
}
請幫助,如果有幫助,我使用sublime文本並通過mcs / mono在終端上編譯。
你應該為main()
輸入參數args
:
static void Main(string[] args)
舉個例子:
class Program {
static void Main(string[] args) {
Console.WriteLine("This is the program");
if (args == null || args.Length == 0) {
Console.WriteLine("This has no argument");
Console.ReadKey();
return;
}
Console.WriteLine("This has {0} arguments, the arguments are: ", args.Length);
for (int i = 0; i < args.Length; ++i)
Console.WriteLine(args[i]);
Console.ReadKey();
}
}
如果您使用參數調用.exe
,程序將顯示:
C:\Release> ConsoleApplication.exe //has no argument
C:\Release> ConsoleApplication.exe Data.txt //has one argument
C:\Release> ConsoleApplication.exe CallWith Data.txt //has two arguments
C:\Release> ConsoleApplication.exe "CallWith Data.txt" //has ONE arguments
在你的情況下,可能參數只是一個字符串,因此,對args[0]
進行輸入檢查就足夠了:
public static void Main(string[] args)
{
if (args == null || args.Length == 0) {
Console.WriteLine("Error: please specify the file to read!");
Console.ReadKey();
return;
}
try {
StreamReader src = new StreamReader(args[0]);
while(!src.EndOfStream)
{
string line = src.ReadLine();
Console.WriteLine(line);
}
} catch (Exception ex) {
Console.WriteLine("Error while reading the file! " + ex.ToString());
}
Console.ReadKey();
}
編輯:
您的最終解決方案應該如下所示(只需將Main塊放到正確的命名空間和類中),您應該使用所有的usings
:
using System;
using System.IO;
namespace ConsoleApplication2 {
class Program {
public static void Main(string[] args) {
if (args == null || args.Length == 0) {
Console.WriteLine("Error: please specify the file to read!");
Console.ReadKey();
return;
}
try {
StreamReader src = new StreamReader(args[0]);
while (!src.EndOfStream) {
string line = src.ReadLine();
Console.WriteLine(line);
}
} catch (Exception ex) {
Console.WriteLine("Error while reading the file! " + ex.ToString());
}
Console.ReadKey();
}
}
}
您可以使用程序的任何位置訪問命令行參數
string[] args = Environment.GetCommandLineArgs();
此外,讀取文件中所有行的最簡單方法是
if (args.Length > 1) //the 1st is always the path to app
string[] lines = System.IO.File.ReadAllLines(ards[1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.