項目中的程序需要自動更新
大概思路
1、通過主程序(判斷是否需要更新)打開更新程序
2、通過更新程序關閉主程序
3、通過更新程序下載壓縮包
4、解壓(新的主程序)
5、打開主程序
在第五步的時候本機測試沒問題,發布到另一台機子之后總是報錯
另一程序正在使用此文件,進程無法訪問....
經過一番排查發現問題出在解壓時沒有釋放文件資源(不知道描述是否准確,另外為什么本機測試不報錯!)
原解壓代碼如下:
public static void UnZip(string fileToUpZip, string zipedFolder, string password)
{
if (!File.Exists(fileToUpZip))
{
return;
}
if (!Directory.Exists(zipedFolder))
{
Directory.CreateDirectory(zipedFolder);
}
ZipInputStream s = null;
ZipEntry theEntry = null;
string fileName;
FileStream streamWriter = null;
try
{
s = new ZipInputStream(File.OpenRead(fileToUpZip));
s.Password = password;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.Name != String.Empty)
{
fileName = Path.Combine(zipedFolder, theEntry.Name);
//判斷文件路徑是否是文件夾
if (fileName.EndsWith("/") || fileName.EndsWith("//"))
{
Directory.CreateDirectory(fileName);
continue;
}
streamWriter = File.Create(fileName);
int size = 2048;
var data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
finally
{
if (streamWriter != null)
{
streamWriter.Close();
streamWriter = null;
}
if (theEntry != null)
{
theEntry = null;
}
if (s != null)
{
s.Close();
s = null;
}
GC.Collect();
GC.Collect(1);
}
}
修改后代碼如下:
public static void UnZip(string fileToUpZip, string zipedFolder, string password)
{
if (!File.Exists(fileToUpZip))
{
return;
}
if (!Directory.Exists(zipedFolder))
{
Directory.CreateDirectory(zipedFolder);
}
using (ZipInputStream zis = new ZipInputStream(File.Open(fileToUpZip, FileMode.Open)))
{
zis.Password = password;
ZipEntry ze = zis.GetNextEntry();
while (ze != null)
{
string fileName = Path.Combine(zipedFolder, ze.Name);
//文件夾
if (fileName.EndsWith("/") || fileName.EndsWith("//"))
{
if (!Directory.Exists(fileName))
{
Directory.CreateDirectory(fileName);
}
}
//文件
else
{
using (FileStream fs = File.Create(fileName))
{
int size = 2048;
var data = new byte[2048];
while (true)
{
size = zis.Read(data, 0, data.Length);
if (size > 0)
{
fs.Write(data, 0, size);
}
else
{
break;
}
}
}
}
ze = zis.GetNextEntry();
}
}
}
希望能幫助到遇見類似問題的同學