How to use Files- Coding Best practices

How to use File Code Best practices

Today in this article, we will learn How to use Files- Coding Best practices to be followed.

Handling files properly (being an unmanaged resource) is important and since all file operation uses OS-level operation behind the picture, it’s important to take care of the file handles including read operation or file create or delete operation.

Today in this article, we will cover below aspects,

We will use generic guidelines and will see a few examples using C# code. However, you can use the discussed approaches for any coding language.

Understand File Enumeration – File Best practices

While using FileStream class, you get the ability to specify the FileShare access type another process that can have while dealing with File Processing.

Example of FileShare Enumeration,

Example

     using (FileStream stream = File.Open(filePath,FileMode.OpenOrCreate,               FileAccess.ReadWrite, FileShare.ReadWrite))
            {


                /// You logic here////
            }

There are 5 enumerations that can be used which define the file access level.

FileShare.None

  • Allows subsequent opening of the file for reading. If this flag is not specified,
  • Any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified,
  • Additional permissions might still be needed to access the file.


FileShare.Read

  • Allows subsequent opening of the file for Reading. If this flag is not specified.
  • Any request to open the file for writing (by this process or another process will fail until the file is closed. However, even if this flag is specified
  • Additional permissions might still be needed to access the file.


FileShare .Write

  • Allows subsequent opening of the file for reading or writing.
  • If this flag is not specified, any request to open the file for reading or writing (by this processor or another process) will fail until the file is closed.
  • However, even if this flag is specified, additional permissions might still be needed to access the file

FileShare .Delete

Allows subsequent deleting of a file.

Proper use of FileShare enumeration will help you resolve the most common issues while dealing with files.

Implements IDisposable for Files

Dealing with File instances or handle is important.

Most file methods are actually core OS-level methods and their associated behavior is determined in the run time.

These file-level classes come under unmanaged resources and hence implement an IDisposable interface in C# language.

Other languages will also have their own way of managing file objects

How to use File in C NET Best practicesHow to use Files Coding Best practices

It’s always safe to use the “using” statement while dealing with files instead of creating and managing the instance ourselves.

Wrap all your code inside “using” statements. it opens the file for reading and writes and closes the file handle once the code scope goes out of using statement.

File in C NET Best practices

Implement a Retry pattern for File processing

This is not mandatory but always come in handy while dealing with file exceptions or temporary glitch accessing the file.

The retry mechanism is a very basic and common pattern for I/O operations.

Example :

Retry(() =>PerformFileProcessing(filePath), 3);

Here method PerformFileProcessing performs all file read or write operations.

Example Simple retry pattern

Implement Thread Synchronization for File -Lock and Unlock

The file can be accessed by multiple threads within the application or by external process threads.

If you have multiple threads attempting to access the same file, consider using a Synchronization mechanism using Lock or another threading synchronization mechanism.

Example

 public class WiteToFileUsingLock
    {
        public string Filepath { get; set; }
        private static object lockerFile = new Object();

        public void WriteToFile(StringBuilder text)
        {
            lock (lockerFile)
            {
                using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                {
                    writer.Write(text.ToString());
                }
            }

        }
    }

Watch if the File is in use by another process

Please make sure to verify the file is not opened by another process. If Yes make sure to handle the scenario gracefully. You could retry or exit the operation based on the need.

This could be any specific process on the system or program opening the file at the time when your program or application is already using it. Closing or stopping the other process may resolve the access issue.

There are multiple ways to deal with File Open, Creating, Reading, or writing operations using C# code. Its important to how different methods are being used in the code.

A few examples of File related methods but not limited are as below,

File.Create

File.Open

File.ReadAllText()

File.WriteAllText()

File.ReadAllLines()

File.WriteAllLines()

The above method allows performing Read or writing conveniently.

Example

          
            // Create the file, or overwrite if the file exists.

            using (FileStream fs = File.Create(path))
            {
                byte[] info = new UTF8Encoding(true).GetBytes("This is test file.");

                // Add details to the file.
                fs.Write(info, 0, info.Length);
            }

          

Note: When using File.Create, please note FileShare value of None is used as default behavior i.e no other process or code can access the file until the original file handle is closed.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *