Share via

How to allow a file to be read but not written to when my app is using the file?

Cynolycus 285 Reputation points
2023-12-18T11:58:35.2733333+00:00

I have two text files that store information that my Windows Forms App uses.

I usually open the files in Excel to view the changes my app is making to them but if I leave it open and start my app the app generates an error because the file is open.

I now have code in place that stops the app from starting if the files are in use but if the file is opened while the app is running, the app doesn't like it and crashes.

I am thinking that when my app starts it needs to prevent the files from being opened by another process while my app is running.

With other programs like Word you could open a file that was already in use by another process but it would be opened in readonly mode.

Is there a way that I can get my app to allow the files to be read but not written to?

Developer technologies | VB
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,241 Reputation points Microsoft External Staff
    2023-12-18T12:32:20.4+00:00

    Hi @Cynolycus ,

    Please try set the FileShare.Read when you open the file.

    If your application allows users to make data modifications, be sure to save changes regularly and release access to the file promptly so that other applications can open the file read-only after it is released.

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.