Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8678983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T20:51:32+00:00 2026-06-12T20:51:32+00:00

Resolution from comments: Application crash was caused by another issue I am reading/writting to

  • 0

Resolution from comments:
Application crash was caused by another issue

I am reading/writting to a file from 2 different applications, when the file is being read or written to, it will always be locked by app A or B and they both make use of FileShare.None.

My issue is that even wrapping the reader around try/catch it still crashes the application with IOException at the using line (does not happen with the writter).

I have also made the catch as catch (IOException ... which I believe makes no difference other then make it more readable.

What is the correct way to ignore when the file is locked and keep trying until the file is available ?

while (true)
{
    try
    {
        using (FileStream stream = new FileStream("test_file.dat", FileMode.Open, FileAccess.Read, FileShare.None))
        {
            using (TextReader reader = new StreamReader(stream))
            {
                // bla bla bla does not matter
            }
        }
    }
    catch
    {
        // bla bla bla does not matter again
    }
    Thread.Sleep(500);
}

Write

private bool WriteData(string data)
{
    try
    {
        using (FileStream stream = new FileStream("test_file.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
        {
            stream.SetLength(0);
            using (TextWriter writer = new StreamWriter(stream))
            {
                writer.Write(data);
            }
        }
        return true;
    }
    catch
    {
        return false;
    }
}

Please note that I am not giving share rights (both writer and reader use FileShare.None) to anyone when the file is being used for whatever process be it reading or writting so basically I am handling the exception until the file is available which is not working.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T20:51:33+00:00Added an answer on June 12, 2026 at 8:51 pm

    Here is the code we use for this purpose.

    /// <summary>
    /// Executes the specified action. If the action results in a file sharing violation exception, the action will be
    /// repeatedly retried after a short delay (which increases after every failed attempt).
    /// </summary>
    /// <param name="action">The action to be attempted and possibly retried.</param>
    /// <param name="maximum">Maximum amount of time to keep retrying for. When expired, any sharing violation
    /// exception will propagate to the caller of this method. Use null to retry indefinitely.</param>
    /// <param name="onSharingVio">Action to execute when a sharing violation does occur (is called before the waiting).</param>
    public static void WaitSharingVio(Action action, TimeSpan? maximum = null, Action onSharingVio = null)
    {
        WaitSharingVio<bool>(() => { action(); return true; }, maximum, onSharingVio);
    }
    
    /// <summary>
    /// Executes the specified function. If the function results in a file sharing violation exception, the function will be
    /// repeatedly retried after a short delay (which increases after every failed attempt).
    /// </summary>
    /// <param name="func">The function to be attempted and possibly retried.</param>
    /// <param name="maximum">Maximum amount of time to keep retrying for. When expired, any sharing violation
    /// exception will propagate to the caller of this method. Use null to retry indefinitely.</param>
    /// <param name="onSharingVio">Action to execute when a sharing violation does occur (is called before the waiting).</param>
    public static T WaitSharingVio<T>(Func<T> func, TimeSpan? maximum = null, Action onSharingVio = null)
    {
        var started = DateTime.UtcNow;
        int sleep = 279;
        while (true)
        {
            try
            {
                return func();
            }
            catch (IOException ex)
            {
                int hResult = 0;
                try { hResult = (int) ex.GetType().GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ex, null); }
                catch { }
                if (hResult != -2147024864) // 0x80070020 ERROR_SHARING_VIOLATION
                    throw;
                if (onSharingVio != null)
                    onSharingVio();
            }
    
            if (maximum != null)
            {
                int leftMs = (int) (maximum.Value - (DateTime.UtcNow - started)).TotalMilliseconds;
                if (sleep > leftMs)
                {
                    Thread.Sleep(leftMs);
                    return func(); // or throw the sharing vio exception
                }
            }
    
            Thread.Sleep(sleep);
            sleep = Math.Min((sleep * 3) >> 1, 10000);
        }
    }
    

    Example of use:

    Utilities.WaitSharingVio(
        action: () =>
        {
            using (var f = File.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                // ... blah, process the file
            }
        },
        onSharingVio: () =>
        {
            Console.WriteLine("Sharing violation. Trying again soon...");
        }
    );
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Objective is to read a list of domains from a file and perform lookup
I'm trying use this code to get image resolution from file bool GetImageSizeEx(const char
How can I get a screen resolution of Device from settings (Windows Phone) ?
I need high-resolution (more accurate than 1 millisecond) timing in my application. The waitable
I read from http://www.apple.com/iphone/specs.html that IPhone4's screen is 960-by-640-pixel resolution at 326 ppi. But
Does JavaScript provide a high resolution timer? I've written a few game engines from
Hi I want to create a google maps like interface from very high resolution
I'm trying to implement a bicubic interpolation algorithm to reconstruct higher-resolution data from a
I want to use ASP.NET Application Services but configure it to use a different
How to get the monitor screen resolution from a hWnd? I am using a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.