主要内容:
- TXT文件读取、写入
- 文件夹/目录创建、删除、移动、计算文件夹大小
基本代码:
测试及文件夹操作using System;
using System.IO;
using csdemo.basic.StreamDemo;
namespace csdemo.basic
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.txtManage();
}
}
class Test
{
public void txtManage()
{
Random r = new Random();
// 文件夹操作
if (!Directory.Exists(@"log\"))
{
// 创建文件夹
Directory.CreateDirectory(@"log\");
}
else if (r.Next() % 3 == 0)
{
// 移动文件夹
Directory.Move(Directory.GetCurrentDirectory(), Directory.GetCurrentDirectory()+@"\old\");
// 创建文件夹
Directory.CreateDirectory(@"log\");
}
else if (r.Next() % 3 == 1)
{
// 删除文件夹,且删除所有子目录
Directory.Delete(@"log\",true);
// 创建文件夹
Directory.CreateDirectory(@"log\");
}
else
{
// 计算文件夹大小
long size = 0;
DirectoryInfo d = new DirectoryInfo(@"log\");
FileInfo[] fi = d.GetFiles();
foreach (FileInfo fin in fi)
{
size += fin.Length;
}
Console.WriteLine("文件夹大小:" + size);
}
string txtName; // 欲操作的文件名
txtName = DateTime.Now.ToString("yyyyMMdd");
TextManager tm = new TextManager(@"log\" + txtName + ".txt");
for(int i=0;i<10;i++)
{
if (!tm.write(@"log\" + txtName + ".txt", i.ToString()))
{
Console.WriteLine("File write ERROR!");
}
}
Console.Write(tm.read(@"log\" + txtName + ".txt"));
Console.ReadLine();
}
}
}
TXT操作类using System.IO;
namespace csdemo.basic.StreamDemo
{
class TextManager
{
FileStream fs;
public TextManager(string txtName)
{
fs = new FileStream(txtName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
fs.Close();
}
public bool write(string txtName,string content)
{
fs = new FileStream(txtName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.WriteLine();
sw.Flush();
sw.Close();
fs.Close();
return true;
}
public string read(string txtName)
{
fs = new FileStream(txtName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.Begin);
string result = sr.ReadToEnd();
sr.Close();
fs.Close();
return result;
}
}
}
参考网摘:
- http://www.cnblogs.com/pegasus923/archive/2011/01/26/1944838.html
- http://www.cnblogs.com/anytao/archive/2006/04/28/387637.html