Validate File Size In C#

To achieve this, we can use the following namespace: "System.IO". Here is a custom code snippet, where the single parameter is the filePath parameter which is for accepting file path to validate size.
  1. public void ValidateFileSize(string filePath) {  
  2.  if (!File.Exists(filePath)) {  
  3.   //Throw error if file not found    
  4.  }  
  5.  FileInfo fileInfo = new FileInfo(filePath);  
  6.  //Validate Length     
  7.  if (fileInfo.Length / 1048 > 20) {  
  8.   //Throw error if file size is larger than your default/set size.    
  9.  }  
  10. }  
Related tutorial