Downloading file with WebRequest - What if file gets replaced on server?

mcravenufo

Ravenufo's Macs
Joined
Feb 28, 2001
Messages
5,590
I am using C# to download a file with WebRequest. Does anyone know how C# handles the case where the file is being read by the client when it gets replaced on the server?

Code:
// simple app so hardcoding this for now
string URL = @"http://downloads.domain.com/dir/" + FileName;

// Create a request for the URL.
WebRequest Request = WebRequest.Create(URL);

Request.Proxy = null;

// If required by the server, set the credentials.
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(URL), "Basic", new NetworkCredential("log", "pass"));
Request.Credentials = credCache;

// Get the response.
HttpWebResponse Response;
try
{
	Response = (HttpWebResponse)Request.GetResponse();
}
catch
{
	FileName = srReadSourceFile.ReadLine();
	continue;
}
// Get the stream containing content returned by the server.
Stream DataStream = Response.GetResponseStream();

// Open the stream using a StreamReader for easy access.
StreamReader srReadData = new StreamReader(DataStream);

string ResponseFromServer = srReadData.ReadToEnd();

// Cleanup the streams and the response.
srReadData.Close();
DataStream.Close();
Response.Close();

StreamWriter swWriteData;
swWriteData = File.CreateText(Directory.GetCurrentDirectory() + "\\" + FileName);
swWriteData.WriteLine(ResponseFromServer);

swWriteData.Close();
 
It probably depends on how the server handles it. Your download might continue and replacing the file might throw a file in use error, your download end prematurely as the file how been replaced, your download might continue because the server cache'd the whole file before it was replaced, etc. My guess, however, is that if the server doesn't have a lock on the file, your download will stop as it's replaced.
 
Back
Top