[英]How to save output redirect to a file?
New to C# and want to implement below reading from input.txt
and write result to output.txt
C#的
input.txt
,想实现从input.txt
读取以下内容并将结果写入output.txt
myprogram.exe < input.txt > output.txt
my code as below 我的代码如下
class Program
{
static void Main(string[] args)
{
String line = Console.ReadLine();
while(line != null)
{
Console.Out.WriteLine(line);
line = Console.ReadLine();
}
}
}
The result is reading from input.txt is fine, and output.txt can be created but nothing in it. 结果是从input.txt读取是可以的,可以创建output.txt,但是其中没有任何内容。
UPDATE: the rootcause is output.txt been locked by other process which is not C# language related. 更新:根本原因是output.txt被与C#语言无关的其他进程锁定。
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; }
}
}
You haven't read documentation at all. 您根本没有阅读过文档。 Here you have the link: click
在这里,您具有链接: 单击
You should just do it in 2 steps: 您只需执行以下两个步骤即可:
string[]
string[]
string[]
string[]
写入文件string[]
To read use 阅读使用
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
To write use 写使用
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
Whole function would look something like this: 整个函数如下所示:
private void CopyFromFileToFile(string inputFileDest, string outputFileDest)
{
string[] lines;
lines = System.IO.File.ReadAllLines(inputFileDest);
System.IO.File.WriteAllLines(outputFileDest, lines);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.