小记怡情
public static class FileHelper
{
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool JudgeFileExist(string path)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
return File.Exists(path);
}
/// <summary>
/// 创建文件
/// </summary>
/// <param name="path"></param>
public static void CreateFile(string path)
{
if (string.IsNullOrEmpty(path))
{
return;
}
try
{
File.Create(path);
}
catch
{
// About 是我自定义的弹窗
App.Current.Dispatcher.Invoke((Action)(() => { new About("提示", "", "路径格式不正确!",false).ShowDialog(); }));
//MessageBox.Show("路径格式不正确。");
}
}
/// <summary>
/// 从txt文件中读取数据
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetStringFromTXT(string path)
{
try
{
if (string.IsNullOrEmpty(path))
{
return string.Empty;
}
using (StreamReader sr = new StreamReader(path))
{
return sr.ReadToEnd();
}
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// 根据路径删除文件
/// </summary>
/// <param name="path"></param>
public static void DeleteFile(string path)
{
FileAttributes attr = File.GetAttributes(path);
if (attr == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
File.Delete(path);
}
}
public static void WriteIntoTXT(string path, string data)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
//获得字节数组
byte[] dataByte = Encoding.Default.GetBytes(data);
//开始写入
fs.Write(dataByte, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
}
public static string GetFileNameByPathWithExtension(string path)
{
string name = string.Empty;
if (!string.IsNullOrEmpty(path))
{
name = path.Substring(path.LastIndexOf("\\") + 1);
}
return name;
}
}