C#读取文件,修改文件数据
想读取一个.txt文件,读取文件中所有内容,把以/开头的这一行全部删除掉,再清空.txt文件中内容,最后把读入并且修改好的内容重新读入到.txt文件中,如何实现。 --------------------编程问答-------------------- 如果不会编程,你可以使用 UltraEdit 或者 EditPlus 来做。 --------------------编程问答--------------------StreamReader sr = new StreamReader(Server.MapPath("name.txt"));
List<string> lsStr = new List<string>();
while (!sr.EndOfStream)
{
lsStr.Add(sr.ReadLine());
}
sr.Close();
StreamWriter sw = new StreamWriter(Server.MapPath("name.txt"));
foreach (string str in lsStr)
{
if(str.Substring(0,1)!="/")
sw.WriteLine(str);
}
sw.Close(); --------------------编程问答--------------------
private static void rwtxt()
{
string filePath = "C;\\test.txt";
StreamReader sr = new StreamReader(filePath);//读对象
List<string> list = new List<string>();
while (!sr.EndOfStream)
{
list.Add(sr.ReadLine());
}
sr.Close();
StreamWriter sw = new StreamWriter(filePath, false);//写对象
foreach (string str in list)
{
if (!str.StartsWith("/"))
sw.WriteLine(str);
}
sw.Close();
}
到时只需改变文件路径位置。 --------------------编程问答-------------------- 一行一行读取记事本里面的数据和一行行写入数据
http://blog.sina.com.cn/s/blog_6c0affba0100qc9s.html --------------------编程问答-------------------- . --------------------编程问答-------------------- 详细解答在:C#清空文件与复写内容的实现
--------------------编程问答--------------------
void openfile(string path)
{
Stream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
StreamReader sr = new StreamReader(fs);
StringBuilder sb = new StringBuilder();
string currentLine = string.Empty;
while ((currentLine = sr.ReadLine()) != null)
{
if (!currentLine.StartsWith("/"))
{
sb.Append(currentLine);
sb.Append("\r\n");
}
}
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
StreamWriter sw = new StreamWriter(fs);
sw.Write(sb.ToString());
sw.Close();
sr.Close();
fs.Close();
}
string path = Server.MapPath("txttxt.txt");--------------------编程问答-------------------- 什么样的方式性能高啊?读取大文件用什么方式好呢 --------------------编程问答-------------------- "把以/开头的这一行全部删除掉,再清空.txt文件中内容"
string[] lineAll = File.ReadAllLines(path, Encoding.GetEncoding("gb2312"));
StringBuilder sb = new StringBuilder();
foreach (string s in lineAll)
{
if (!s.StartsWith("/"))
sb.Append(s).Append("\r\n");
}
File.WriteAllText(path, sb.ToString());
这样和直接清空文件内容有什么区别吗? --------------------编程问答--------------------
using(FileStream xx= new FileStream(文件路径,模式如 FileMode.Open))
{
读取文件方法,方法返回一个int型的本次读取的长度
int length = xx.Read(用来保存读出的数据的字节型数组,读取字节的开始下标也就是文件字节总长度的第几位,本次读取的数据长度)
} --------------------编程问答-------------------- --------------------编程问答--------------------
直接把文件删除了,重新输出个文件 --------------------编程问答--------------------
我也是这么想的。。。
补充:.NET技术 , C#