在开发过程中,难免我们会对系统的文件进行一些操作。这里是我对文件操作的一些整理
在App.config配置文件:
<appSettings>
<!--日志路径-->
<add key="LogPath" value="C:\Users\zwl\Desktop\IO\IO\File"/>
<add key="NewLogPath" value="C:\Users\zwl\Desktop\IO\IO\NewFile"/>
</appSettings>
定义类:
public class MyIO
{
//设置静态字段只需要初始化一次,下次可以直接调用,放在缓存中
private static string LogPath = ConfigurationManager.AppSettings["LogPath"];
private static string NewLogPath = ConfigurationManager.AppSettings["NewLogPath"];
public void Show()
{
try
{
#region 对文件目录的操作
//检测目录是否存在
if (!Directory.Exists(LogPath))
{
//如果目录不存在
DirectoryInfo directory = Directory.CreateDirectory(LogPath);//再指定路径中创建所有目录和子目录
Directory.Move(LogPath, NewLogPath);//将文件或目录及其内容移动到新的位置
Directory.Delete(LogPath);//删除
}
#endregion
#region 对文件的操作
string fileName = Path.Combine(LogPath, "log.txt");//将两个字符串合成一个路径
string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
string fileNameMove = Path.Combine(NewLogPath, "logMove.txt");
//检测指定文件是否存在
if (!File.Exists(fileName))
{
Directory.CreateDirectory(LogPath);//首先创建文件夹,才能创建里面的文件
//----------------------------------对文件的写----------------------------------
using (FileStream fileStream = File.Create(fileName))//打开文件流(创建文件并写入)
{
string str = "123456";
Byte[] bytes = Encoding.Default.GetBytes(str);
fileStream.Write(bytes,0,bytes.Length);//将字节块写入缓存流
fileStream.Flush();//清除此流的缓存区
}
//同名的文件夹会被覆盖
using (FileStream fileStream = File.Create(fileName))//打开文件流(创建文件并写入)
{
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine("1234567890123");
fileStream.Flush();
}
//同名的文件,内容会被添加进去
using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
{
string msg = "脱裤子放屁";
sw.WriteLine(msg);
sw.Flush();
}
using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入)
{
string str = "123456789";
Byte[] bytes = Encoding.Default.GetBytes(str);
sw.BaseStream.Write(bytes,0,bytes.Length);
sw.Flush();
}
//----------------------------------对文件的写----------------------------------
//读取文件的所有行
foreach (string item in File.ReadAllLines(fileName))
{
Console.WriteLine(item);
}
//text方式读取
string sResult = File.ReadAllText(fileName);
//byte方式读取
Byte[] byteContent = File.ReadAllBytes(fileName);
string sResultByte = Encoding.UTF8.GetString(byteContent);
//获取最后一行数据
StreamReader sr = new StreamReader(fileName);
string c = sr.ReadToEnd();
string[] cs = c.Split(new char[] { '\n', '\r' });
sr.Close();
string lastLine = cs[cs.Length - 1];
Console.WriteLine(lastLine);
//复制
File.Copy(fileName, fileNameCopy);
//移动
File.Move(fileName, fileNameMove);
//删除
File.Delete(fileNameCopy);
File.Delete(fileNameMove);
}
#endregion
}
catch (Exception)
{
throw;
}
}
}
如果有什么好的建议,希望能够得到指正和批评!