File.CreateText创建文件并写入文本
2016-10-10 15:13
537 查看
最近在网上看到许多关于创建文件并写入文本的博文,大概都是以下的方法:
创建一个新文本文件并写入一个字符串:
第二种:用Streamwriter
其实呢,第一种方法最简单。创建一个文件直接写入值,如果你的文本字段只有英文的话,那推荐使用第一种方法,简单嘛。但是这种方法有一个缺陷就是它缺乏支持中文的元素。
你只要输入sw.WriteLine ("我的博客.");这下惨了,出来的全是乱码。
第二种方法呢又不能直接创建文件。哎。。。。真是杯具啊。。。
经过实验,发现一种简单的方法:发出来共享下
第三种方法:
创建一个新文本文件并写入一个字符串:
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();
相关文章推荐
- Java 源码 ——顺序存取文件的创建及写入(Writing data to a sequential text file with class Formatter)
- C# winform 创建新文件--写入文本并另存为
- android文件的写入与读取---简单的文本读写context.openFileInput() context.openFileOutput()
- 统计文本文件信息(Calculating Text File Statistics)
- js document.createTextNode()创建文本节点详解
- CreateTextFile 文件的使用
- File.WriteAllText 写入TXT文件时不能正确换行只显示方块
- 手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾,其余对应的数据相加,三个文本的内容如下
- 【Android】android文件的写入与读取---简单的文本读写context.openFileInput() context.openFileOutput()
- js document.createTextNode()创建文本节点详解
- android文件的写入与读取---简单的文本读写context.openFileInput() context.openFileOutput()
- 打开大文本文件工具(大于1G的文本文件)——Large Text File Viewer 5.2 - Features
- FileSystemWatch 对文件的监测 修改 创建 删除 并写入日志
- iPhone开发-创建、读取、写入文件 今天的东西是如何在iPhoneOS下创建、删除、读取、写入文件 创建与删除: //创建文件管理器 NSFileManager *fileManager =
- 利用File.Create创建文件存在的问题
- C#使用Create创建文件后,报The Process cannot access the file because it is being used by another process的异常
- File.Create在用这创建文件后,需要关闭,否则在访问这个文件提示文件被占用了
- C#使用File.Create创建文件后,报错另一进程正在使用该文件
- C# SaveFileDialog +FileStream+StreamWriter 创建或者覆盖一个文件,并且写入
- dedecms无法创建rss文件,提示DedeTag Engine Create File False