class FileHelper
{
///
/// 检验文件路径是否合法
///
/// 文件路径
private static bool CheckPath(string path)
{
//正确格式:C:\Users\jcx\Desktop\Test.txt
string pattern = @"\w{1}:([\\].+)*.+\.\w{3,}";
Regex rg = new Regex(pattern);
return rg.IsMatch(path);
}
///
/// 创建一个新的文本文件
///
/// 文件路径
/// 写入到文本的内容
public static void CreateNewTxtFile(string path,string content)
{
if (!CheckPath(path))
{
throw new Exception("文件路径不合法");
}
//存在则删除
if (File.Exists(path))
{
File.Delete(path);
}
using (FileStream fs=new FileStream (path,FileMode.CreateNew,FileAccess.Write))
{
byte[] bt = Encoding.Default.GetBytes(content);
fs.Write(bt,0,bt.Length);
} //using
}
///
/// 读取文本文件
///
/// 文件路径
/// 指定每次读取字节数
/// 读取的全部文本内容
public static string ReadTxtFile(string path,long readByte)
{
if (!CheckPath(path))
{
throw new Exception("文件路径不合法");
}
StringBuilder result = new StringBuilder();
using (FileStream fs=new FileStream (path,FileMode.Open,FileAccess.Read))
{
byte[] bt = new byte[readByte];
while (fs.Read(bt,0,bt.Length)>0) //每次只从文件中读取部分字节数,一点点读
{
string txt = Encoding.Default.GetString(bt); //解码转换成字符串
result.AppendLine(txt);
}
} //using
return result.ToString();
}
}
class Program
{
static void Main(string[] args)
{
string path = @"C:\Users\jcx\Desktop\Test.txt";
FileHelper.CreateNewTxtFile(path, "好好努力");
string r = FileHelper.ReadTxtFile(path,2); //2个字节为一个汉字,一个汉字一个汉字的读
Console.WriteLine(r);
} // Main
}