C# 具体程序 控制台应用程序运行之后的内容怎么保存到记事本里边

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace tasksgeneration
{
class Class1
{
static void Main(string[] args)
{
System.Console.WriteLine("\n控制台应用程序运行之后的内容怎么保存到记事本里边:");
File.CreateText("C:\\Users\\admin\\Desktop\\instance.txt");
// 接下来怎么写,上面是举例,要求将程序运行之后的内容保存到创建的text里
}
}
}
看类似的方法如下
File.WriteAllText(@"C:\a.txt",str,System.Text.Encoding.UTF8);
但是会提示“string”上下文中不存在。小白一枚,求教。
或者
FileStream fs = new FileStream("D:\\A.txt",FileMode.Apend);~~

会提示“Apend”不在“System.IO;”?

当然我的显示程序不止“hallow”“welcome”那么简单,就是把所有的窗体显示内容保存到text文件中

如果输出的内容是你可以控制的,那么用StreamWriter即可,每次输出都调用它的WriteLine方法,最后调用Flush写入即可。也可以自己写一个函数。当然如果要省去命名空间的话需要在代码最上方加上Using System.IO;语句。
Program类中:
StreamWriter consoleWriter = New StreamWriter("D:\\1.txt");
void writeLine(string str)
{
consoleWriter.WriteLine(str);
Console.WriteLine(str);
}
Main函数:
writeLine("hello!");

如果是其它情况,建议你用命令行运行,最后加个>文件名。比如生成的程序是D:\tasksgeneration\bin\Debug\tasksgeneration.exe。打开开始,运行,输入cmd回车,输入D:\tasksgeneration\bin\Debug\tasksgeneration.exe>D:\1.txt然后就可以了追问

是第二种情况,但是有没有一步到位的。比如运行.exe或者启动调试就一步生成的
另外,参考别人的方法如下:
运行用系统的重定向就可以了.
xxx.exe>output.txt
这里的重定向什么意思,如何实现

追答

你可以在另外一个项目里面运行cmd /c 路径>D:\a.txt来实现。其实就是把输出内容写到文件里去

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-01-25
using (StreamWriter sw = new StreamWriter("E:\\a.txt", true))
{
sw.WriteLine("锄禾日当午");
sw.Flush();
}

StringWriter实例化的时候。有重载. 设置是否覆盖。或者追加等等..

sw.Write("字符串");
你想写多少写多少。...
操作文件的方法很多...

定义一个StringBuilder s= new StringBuilder();
s.Append("1");
s.Append("2");
s.Append("3");
s.Append("4");
s.Append("5");
把你需要的内容 拼成字符串 然后使用上面的 sw.Writer(s.ToString());
就可以了
第2个回答  2014-01-25
相似回答