分享一下操作文件得常用方法可以直接拿来用哦(读取文件,解压Zip,Rar)

/// <summary>
/// 读取文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="encode">编码</param>
/// <returns></returns>
public static string ReadFile(string Path, Encoding encode)
{
Dictionary<int, string> dic = new Dictionary<int, string>();
StringBuilder sb = new StringBuilder();
try
{
LogWriteLock.EnterReadLock();
if (!System.IO.File.Exists(Path))
{
sb = null;
}
else
{
StreamReader f2 = new StreamReader(Path, encode);
String line;
int i = 0;
while ((line = f2.ReadLine()) != null)//按行读取 line为每行的数据
{
i++;
dic.Add(i, line);
}
foreach (var item in dic)
{
sb.Append(item.Value);
}
f2.Close();
f2.Dispose();
}
}
catch (Exception)
{

}
finally
{
LogWriteLock.ExitReadLock();
}
return sb?.ToString();
}

/// <summary>
/// 解压Zip
/// </summary>
/// <param name="sourcePath">源文件</param>
/// <param name="targetPath">解压文件路径</param>
/// <returns></returns>
public static bool CompressZip(string sourcePath, string targetPath)
{
try
{
ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(sourcePath));//待解压的文件
ArrayList fileStr = new ArrayList();
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(targetPath);//解压后放置的目标目录
var fileName = Path.GetFileName(theEntry.Name);
//生成解压目录
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
if (fileName != String.Empty)
{
//解压文件到指定的目录
FileStream streamWriter = System.IO.File.Create(Path.Combine(targetPath, theEntry.Name));
long totalSize = streamWriter.Length;
int size = 1024;
byte[] data = new byte[1024];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
fileStr.Add(Path.Combine(targetPath, fileName));
}
}
s.Close();
System.IO.File.Delete(sourcePath);
return true;
}
catch (Exception e)
{
return false;
}
}

/// <summary>
/// 解压Rar
/// </summary>
/// <param name="sourcePath">源文件</param>
/// <param name="targetPath">解压文件路径</param>
/// <returns></returns>
public static bool CompressRar(string sourcePath, string targetPath)
{
try
{
using (Stream stream = System.IO.File.OpenRead(sourcePath))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
reader.WriteEntryToDirectory(targetPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
}
return true;
}
catch (Exception e)
{
return false;
}
}

posted @ 2022-04-12 14:26  薛小谦  阅读(75)  评论(0编辑  收藏  举报