判断文件是否被进程使用
public static bool IsFileInUse(string fileName)
{
bool inUse = true;
FileStream fs = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,FileShare.None);
inUse = false;
}
catch
{
}
finally
{
if (fs != null)
fs.Close();
}
return inUse;//true表示正在使用,false没有使用
}
文件夹复制
public static void CopyDirectory(string srcPath, string destPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileInfo = dir.GetFileSystemInfos();
foreach (FileSystemInfo file in fileInfo)
{
if (file is DirectoryInfo)
{
if (!Directory.Exists(destPath + "\\" + file.Name))
{
Directory.CreateDirectory(destPath + "\\" + file.Name);
CopyDirectory(file.FullName, destPath + "\\" + file.Name);
}
}
else
{
if (!File.Exists(destPath + "\\" + file.Name))
{
File.Copy(file.FullName, destPath + "\\" + file.Name);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"从{srcPath}复制到{destPath}出现异常,消息:{ex.Message}");
//throw;
}
}
解压文件
public bool UnZip(string zipFilePath, string unZipDir)
{
string pathZip = Path.GetFileNameWithoutExtension(zipFilePath) + "Zip";
unZipDir = Path.Combine(unZipDir, pathZip) + "//";
if (Directory.Exists(unZipDir))
{
DirectoryInfo di = new DirectoryInfo(unZipDir);
di.Delete(true);
}
if (zipFilePath == string.Empty)
{
IsToZip = false;
return false;
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath))
{
IsToZip = false;
return false;
throw new FileNotFoundException("压缩文件不存在!");
}
while (IsFileInUse(zipFilePath))
{
Thread.Sleep(2);
}
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
try
{
using (var fileStream = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var s = new ZipInputStream(fileStream))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
Thread.Sleep(3000);
string fileName = Path.GetFileName(theEntry.Name);
if (fileName != String.Empty)
{
if (!File.Exists(unZipDir + theEntry.Name))
{
FileStream streamWriter = File.Create(unZipDir + theEntry.Name);
Thread.Sleep(4000);
int size;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
}
}
}
}
catch (Exception ex)
{
IsToZip = false;
MessageBox.Show($"解压文件出现错误:{ex.Source}。错误信息:{ex.Message}");
return false;
}
return true;
}