C#的新用户,希望在input.txt
下方读取并将结果写入output.txt
myprogram.exe < input.txt > output.txt
我的代码如下
class Program
{
static void Main(string[] args)
{
String line = Console.ReadLine();
while(line != null)
{
Console.Out.WriteLine(line);
line = Console.ReadLine();
}
}
}
结果是从input.txt读取是正常的,并且可以创建output.txt但其中没有任何内容。
更新:rootcause是output.txt被其他与C#语言无关的进程锁定。
答案 0 :(得分:0)
using System;
using System.IO;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
var parameters = GetParameters(args);
var inputContent = GetInputContent(parameters);
CreateOutputFile(parameters, inputContent);
Console.WriteLine("it's ok. Press key to exit");
Console.ReadKey();
}
private static void CreateOutputFile(MyProgramParameters parameters, string inputContent)
{
File.WriteAllText(parameters.OutputFileName, inputContent);
}
private static string GetInputContent(MyProgramParameters parameters)
{
var result = File.ReadAllText(parameters.InputFileName);
return result;
}
private static MyProgramParameters GetParameters(string[] args)
{
CheckInputParameters(args);
return new MyProgramParameters
{
InputFileName = args[0],
OutputFileName = args[1]
};
}
private static void CheckInputParameters(string[] args)
{
if (args.Length != 2)
throw new ArgumentException("invalid parameters. For example, myProgram.exe input1.txt output.txt");
var inputFileName = args[0];
if (!File.Exists(inputFileName))
throw new IOException(string.Format("File {0} not found", inputFileName));
}
}
public class MyProgramParameters
{
public string InputFileName { get; set; }
public string OutputFileName { get; set; }
}
}
答案 1 :(得分:0)
您根本没有阅读文档。这里有链接:click
你应该分两步完成:
string[]
string[]
阅读用途
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
写使用
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
整个功能看起来像这样:
private void CopyFromFileToFile(string inputFileDest, string outputFileDest)
{
string[] lines;
lines = System.IO.File.ReadAllLines(inputFileDest);
System.IO.File.WriteAllLines(outputFileDest, lines);
}