文件操作类库(请加群 480888314 互动交流 分享干货)
/// <summary>
/// 保存文件
/// </summary>
/// <param name="filename"></param>
/// <param name="byt"></param>
/// <returns></returns>
public bool Save(string filename, byte[] byt)
{
try
{
string _FileSave = GetFilePath() + filename;
string UploadPath = System.IO.Path.GetDirectoryName(_FileSave);
if (!Directory.Exists(UploadPath))
{
Directory.CreateDirectory(UploadPath);
ExecptionRecord.WriteExecptionToFile("","创建目录" + UploadPath + "!");
}
FileStream fs = new FileStream(_FileSave, FileMode.Append, FileAccess.Write);//+ filename
fs.Write(byt, 0, byt.Length);
fs.Close();
fs.Dispose();
return true;
}
catch (Exception err)
{
ExecptionRecord.WriteExecptionToFile("","发生错误" + err.ToString());
try
{
string UploadPath = GetFilePath();
string DelFileName = UploadPath + filename;
if (File.Exists(DelFileName))
{
File.Delete(DelFileName);
}
}
catch (Exception err2)
{
ExecptionRecord.WriteExecptionToFile("", "发生错误" + err2.ToString());
}
return false;
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="FileName"></param>
/// <returns></returns>
public bool DeleteFile(string FileName)
{
try
{
string UploadPath = GetFilePath();
string DelFileName = UploadPath + FileName;
if (File.Exists(DelFileName))
{
File.Delete(DelFileName);
ExecptionRecord.WriteExecptionToFile("", "删除文件" + DelFileName);
}
return true;
}
catch (Exception err)
{
ExecptionRecord.WriteExecptionToFile("", "发生错误" + err.ToString());
return false;
}
}
/// <summary>
/// 获取文件的长度
/// </summary>
/// <param name="FileName">文件名</param>
/// <returns></returns>
public long GetFileLenth(string FileName)
{
try
{
string UploadPath = GetFilePath();
string FilePath = UploadPath + FileName;
if (File.Exists(FilePath))
{
FileInfo f = new FileInfo(FilePath);
long Len = f.Length;
return Len;
}
else
{
return 0;
}
}
catch(Exception err)
{
ExecptionRecord.WriteExecptionToFile("", "发生错误" + err.ToString());
return 0;
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="fileName">文件的名字,不含路径</param>
/// <param name="offset">偏移量</param>
/// <param name="length">读取字节的长度</param>
/// <returns>如果正确则返回字节数组</returns>
public byte[] ReadFileBtyes(string fileName, int offset, out int length)
{
length = 0;
fileName = GetFilePath() + fileName;
if (!System.IO.File.Exists(fileName))
{
return null;
}
byte[] bts = new byte[1024 * 5];
FileStream fs = null;
try
{
fs = File.OpenRead(fileName);
fs.Seek(offset, SeekOrigin.Begin);
length = fs.Read(bts, 0, bts.Length);
fs.Close();
if (length > 0)
{
return bts;
}
}
catch (Exception err)
{
ExecptionRecord.WriteExecptionToFile("", "发生错误" + err.ToString());
if (fs != null)
{
fs.Close();
}
}
return null;
}