您的位置:首页 > 编程语言 > C#

File.CreateText创建文件并写入文本

2016-10-10 15:13 537 查看
最近在网上看到许多关于创建文件并写入文本的博文,大概都是以下的方法:
创建一个新文本文件并写入一个字符串:
using System;
using System.IO;
public class TextToFile
{
private const string FILE_NAME = "MyFile.txt";
public static void Main(String[] args)
{
if (File.Exists(FILE_NAME)) // 确认文件是否存在.
{
Console.WriteLine("{0} already exists.", FILE_NAME);
return;
}
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
sw.WriteLine ("This is my file.");
sw.WriteLine ("I can write ints {0} or floats {1}, and so on.",
1, 4.2);
sw.Close();
}
}
}

第二种:用Streamwriter
using System;
using System.IO;
class Test
{
public static void Main()
{
// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter("TestFile.txt"))
{
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}
}
}

其实呢,第一种方法最简单。创建一个文件直接写入值,如果你的文本字段只有英文的话,那推荐使用第一种方法,简单嘛。但是这种方法有一个缺陷就是它缺乏支持中文的元素。
你只要输入sw.WriteLine ("我的博客.");这下惨了,出来的全是乱码。
第二种方法呢又不能直接创建文件。哎。。。。真是杯具啊。。。
经过实验,发现一种简单的方法:发出来共享下
第三种方法:
string path=Server.MapPath(你的路径);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true, System.Text.Encoding.Default);
                sw.Write(context);
                sw.Close();
                sw.Dispose();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 写入文件
相关文章推荐