Hi,
I am developing amobile device app. with VS 2005 and c#. At start up the app checks if there is an update for any of the files (via web service), if there is any they get downloaded and the actual application exe is started.
Now, whenever I do an update, everything seems ok. Next time I try to do the same thing, I get an error. It seems the files are locked. I cannot delete/copy them manually or by code. I believe it is my code locking it but I need more eyes to find which bit of code is doing it. Below I post most of my code dealing with file download/update.
It starts with the code below. The code uses the backgroundworker component from D Moth.
foreach (XmlNode node in files)
{
if (node != null)
{
count++;
// Get the file name of the current updated file.
file = node.InnerXml;
if (file.Length > 0)
{
Application.DoEvents();
// Download the file to our temp directory.
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(Utils.H
ttpDownloa
d);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHan
dler(worke
r_RunWorke
rCompleted
);
BackgroundWorkerArgs args = new BackgroundWorkerArgs();
args.DownloadSource = url + file;
args.DownloadDestination = AppDir + UpdatesTempDir + file;
workers.Add(worker);
workers[workers.Count -1].RunWorkerAsync(args);
}
}
}
This above results a call made to HttpDownload in Utils class. The mothods are below
public static void HttpDownload(object sender, DoWorkEventArgs e)
{
BackgroundWorkerArgs args = (BackgroundWorkerArgs)e.Ar
gument;
HttpDownload(args.Download
Source, args.DownloadDestination);
}
public static bool HttpDownload(string source, string destination)
{
bool downloaded = false;
HttpWebRequest request = null;
HttpWebResponse response = null;
FileStream newFile = null;
BinaryReader reader = null;
BinaryWriter writer = null;
try
{
lock (syncLock)
{
// Create the destination file. If it exists then overwrite it.
newFile = new FileStream(destination, FileMode.Create, FileAccess.Write);
// Request the source.
request = (HttpWebRequest)HttpWebReq
uest.Creat
e(source);
response = (HttpWebResponse)request.G
etResponse
();
// Read the response.
reader = new BinaryReader(response.GetR
esponseStr
eam());
writer = new BinaryWriter(newFile);
}
}
catch (Exception ex)
{
// Failed trying to create the local file or opening the request.
downloaded = false;
}
try
{
while (true)
{
// Write bytes to the new file.
writer.Write(reader.ReadBy
te());
}
}
catch (System.IO.EndOfStreamExce
ption)
{
// We reached the end of the file.
downloaded = true;
}
catch(System.Exception ex)
{
// Download failed.
downloaded = false;
}
finally
{
// Always close the files.
if (writer != null)
{
writer.Flush();
writer.Close();
}
if (newFile != null)
newFile.Close();
}
return downloaded;
}
On completing each file download, a method on the GUI gets called and is shown below along with methods (those dealing with files) called within it.
void worker_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArg
s e)
{
try
{
currentFileNumber++;
if (currentFileNumber == totalFileCount + 1)
{
// Install the new updates.
this.pbProgress.Value = 100;
this.UpdateProgressLabel("
Installing
updated files...");
System.Threading.Thread.Sl
eep(150);
this.CopyDirectoryNonRecur
se(AppDir + UpdatesTempDir, AppDir, false);
// Update the client config file with the new version number.
this.UpdateProgressLabel("
Reconfigur
ing client components...");
System.Threading.Thread.Sl
eep(150);
UpdateConfig(AppDir + ClientConfigFile, newVersion);
this.UpdateProgressLabel("
New version installed.");
System.Threading.Thread.Sl
eep(150);
// Clear the temp download directory and files.
this.UpdateProgressLabel("
Deleting temporary files...");
System.Threading.Thread.Sl
eep(150);
this.ClearDirectory(AppDir
+ UpdatesTempDir);
currentFileNumber = 0;
totalFileCount = 0;
DoUpdate(true);
}
else
{
this.pbProgress.Value = 90 / totalFileCount * (currentFileNumber - 1);
Application.DoEvents();
this.UpdateProgressLabel("
Downloadin
g file " + currentFileNumber.ToString
() + " of " + totalFileCount + "...\n");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Failed to auto-update", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Bu
tton1);
StartApp();
}
}
private void CopyDirectoryNonRecurse(st
ring sourcePath, string destPath, bool deleteFirst)
{
// Put paths into DirectoryInfo object to validate.
DirectoryInfo dirInfoSource = new DirectoryInfo(sourcePath);
DirectoryInfo dirInfoDest = new DirectoryInfo(destPath);
// Check if destination dir exists.
if (Directory.Exists(dirInfoD
est.FullNa
me))
{
if (deleteFirst)
{
Directory.Delete(dirInfoDe
st.FullNam
e, true);
Directory.CreateDirectory(
dirInfoDes
t.FullName
);
}
}
else
{
// Create the new directory.
Directory.CreateDirectory(
dirInfoDes
t.FullName
);
}
// Copy all files in the directory.
CopyDirFiles(dirInfoSource
.FullName,
dirInfoDest.FullName);
}
private void CopyDirFiles(string sourcePath, string destinationPath)
{
try
{
// Get dir info which may be file or dir info object.
DirectoryInfo dirInfo = new DirectoryInfo(sourcePath);
if (!destinationPath.EndsWith
(@"\"))
{
destinationPath = destinationPath + @"\";
}
foreach (FileSystemInfo fsi in dirInfo.GetFileSystemInfos
())
{
if (fsi is FileInfo)
{
// If file object just copy. Overwrites files!
File.Copy(fsi.FullName, destinationPath + fsi.Name, true);
}
else
{
// Ignore sub directories.
}
}
}
catch (Exception ex)
{
throw;
}
}
private void ClearDirectory(string dir)
{
try
{
// Check if the directory exists.
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
// Create the directory.
Directory.CreateDirectory(
dir);
}
catch (Exception)
{
throw;
}
}
What I am looking for is help to find the code that is leaving files locked. I cannot tell if my application's process is still running. VS remote tools are not working for me. It cannot connect to device! don't know why!
Thanks
H
Start Free Trial