2

I have refresh button. On refresh, I need to download a file and de-serialize its contents to read the information in it. Below is the method used to download the file.

public void DownloadVersionContents(long fileID,string fileName)
        {
            if (File.Exists(path))
              {
                 File.Delete(path);
              }
            Stream stream = service.DownloadContent(fileID);

            using (FileStream fileStream = File.OpenWrite(fileName))
            {
                // Write the stream to the file on disk.
                var buf = new byte[1024];
                int numBytes;
                while ((numBytes = stream.Read(buf, 0, buf.Length)) > 0)
                {
                    fileStream.Write(buf, 0, numBytes);
                }
                fileStream.Close();
            }
            stream.Close();
        }

Everytime the refresh button is clicked, I have to delete the file and download latest file from the server. If the refresh is called with in a second or two im getting an error saying

System.IO.IOException was caught
  HResult=-2147024864
  Message=The process cannot access the file 'C:\Users\...\AppData\Local\Temp\mapping - copy.xml' because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.File.InternalDelete(String path, Boolean checkHost)
       at System.IO.File.Delete(String path)

If the refresh is called after at least 10 or 20 seconds,im not getting any error. The file is never opened nor used yet. Kindly help. Edit: Sorry I forgot to mention, Im de-serializing the file using this method immediately after refresh is called.

public static T DeSerializeFromFile<T>(string xmlFilePath) 
        {
            T instance = default(T);

            if (xmlFilePath != null)
            {
                var reader = new StreamReader(xmlFilePath);
                var serializer = new XmlSerializer(typeof(T));
                instance = (T)serializer.Deserialize(reader);
            }
            return instance;
        }

The refresh button is called again after the values are updated.

3
  • As a side note, the Dispose() method on Stream calls its Close() method (or vice-versa)--there's no need to include that if you're already using a using block, which is good practice. If I were you, I'd wrap stream in a using block, then get rid of both of your calls to Close(). Mar 27, 2015 at 9:15
  • @MatthewHaugen I have tried the way you suggested. But still no luck.
    – Revanth
    Mar 27, 2015 at 9:45
  • You are doing battle with another program on your machine that also wants to access the file. It isn't very sophisticated when it prevents deletion, probably a search indexer, could be anti-malware. You can rename the file first to, say, path + ".bak" to allow you to create the file without that program getting in the way. Then try to delete that .bak file, failure to do so is not fatal. You'll delete it the next time. Or move it to the recycle bin. Mar 27, 2015 at 9:45

2 Answers 2

0

This seems like a good time to use a try catch-block. Catch the exception and prompt the user if the file is busy.

try
{
    if (File.Exists(path))
         File.Delete(path);

    using(Stream stream = service.DownloadContent(fileID))
    {
        using (FileStream fileStream = File.OpenWrite(fileName))
        {
            // Write the stream to the file on disk.
            var buf = new byte[1024];
            int numBytes;
            while ((numBytes = stream.Read(buf, 0, buf.Length)) > 0)
            {
                fileStream.Write(buf, 0, numBytes);
            }
        }
    }
}
catch (IOException e)
{
    MessageBox.Show("The refresh failed, try again in a few seconds."); 
}

This wont speed up the refresh process but it will prevent the user from crashing your program by spamming refresh. Try to always have this kind of exception handling present when working with outside sources.

5
  • Thanks for the reply. I thought this alternative too. If the file is opened I can prompt him saying to close it and try again. But I cannot ask user to try again after 10 or more seconds without any reason.
    – Revanth
    Mar 27, 2015 at 9:34
  • @Revanth The file beeing busy because of a refresh already beeing in progress seems lika a good reason for the user to wait. I'm probably misunderstanding your question, are you asking for help speeding up the refresh and not a way to stop the crashing?
    – Hjalmar Z
    Mar 27, 2015 at 9:43
  • Hjalmar Z, because of the error, the refresh is not happening and the values are not getting updated. User no need to click the refresh button twice but, he might do it and the error is throwing. Refresh the settings is first step after login. So he might tend to do it again and again to make sure they got updated. Please let me if you are still not clear.
    – Revanth
    Mar 27, 2015 at 9:52
  • If the user clicks again, the MessageBox.Show() stops the first refresh operation from completing?
    – Hjalmar Z
    Mar 27, 2015 at 9:59
  • Hjalmar, I want to know, even though all the updates are done, why is it throwing error? If the de serialization is the causing it, why is it taking 10 seconds almost to update some simple string updations? For now im going with your suggestion with try catch and message box. Thanks for the time. If you have any other better idea, please post
    – Revanth
    Mar 27, 2015 at 10:16
0

It sounds like the file takes longer than a couple seconds to get written. If the file is still being written to, then no, you certainly won't be able to delete it. You have a couple options.

The simplest, and probably best, is to keep track of whether you're still writing to it.

private bool IsWriting = false;
public void DownloadVersionContents(long fileID, string fileName)
{
    if (!IsWriting)
    {
        IsWriting = true;

        // Perform the delete and download

        IsWriting = false;
    }
}

Depending on the platform, you might want to reflect this in the UI as well, perhaps by disabling the "Refresh" button. This, of course, is assuming the file doesn't change more frequently than the time it takes to update. If it does, you may want to implement some cancellation pattern.

Beyond that, you could buffer the file directly into memory, then write it "all at once," which would probably only take a fraction of a second. Of course, if it's a big file, that won't be feasible.

1
  • Thanks for the reply. The file is lessthan 3KB. Do you think it will take morethan 2 seconds to download?. Im pretty sure that while loop is finished before calling the another refresh request.
    – Revanth
    Mar 27, 2015 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.