C# common IO methods

public class IoHelper
    {
        /// <summary>
        ///Check whether the file exists
        /// </summary>
        /// <param name="fileName">The file path</param>
        /// <returns>If there is a</returns>
        public static bool Exists(string fileName)
        {
            if (fileName == null || fileName.Trim() == "")
            {
                return false;
            }
            return File.Exists(fileName);
        }


        /// <summary>
        ///Creating a folder
        /// </summary>
        /// <param name="dirName">Folder name</param>
        /// <returns></returns>
        public static bool CreateDir(string dirName)
        {
            try
            {
                if (dirName == null)
                    throw new Exception("dirName");
                if(! Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); }return true;
            }
            catch (Exception er)
            {
                throw newException(er.Message); }}/// <summary>
        ///Create a file
        /// </summary>
        /// <param name="fileName">The file name</param>
        /// <returns>Return false on creation failure</returns>
        public static bool CreateFile(string fileName)
        {
            try
            {
                if (File.Exists(fileName)) return false;
                var fs = File.Create(fileName);
                fs.Close();
                fs.Dispose();
            }
            catch (IOException ioe)
            {
                throw new IOException(ioe.Message);
            }

            return true;
        }


        /// <summary>
        ///Read the content of the file and convert it to a character type
        /// </summary>
        /// <param name="fileName">The file path</param>
        /// <returns></returns>
        public static string Read(string fileName)
        {
            if(! Exists(fileName)) {return null;
            }
            // Read file information into the stream
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                return newStreamReader(fs).ReadToEnd(); }}/// <summary>
        ///Files are converted to Char[] arrays
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static char[] FileRead(string fileName)
        {
            if(! Exists(fileName)) {return null;
            }
            var byData = new byte[1024];
            var charData = new char[1024];
            try
            {
                var fileStream = new FileStream(fileName, FileMode.Open);
                fileStream.Seek(135, SeekOrigin.Begin);
                fileStream.Read(byData, 0.1024);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            var decoder = Encoding.UTF8.GetDecoder();
            decoder.GetChars(byData, 0, byData.Length, charData, 0);
            return charData;
        }



        /// <summary>
        ///File converted to byte[]
        /// </summary>
        /// <param name="fileName">The file path</param>
        /// <returns></returns>
        public static byte[] ReadFile(string fileName)
        {
            FileStream pFileStream = null;
            try
            {
                pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                var r = new BinaryReader(pFileStream);
                // Set the file pointer to file open
                r.BaseStream.Seek(0, SeekOrigin.Begin);
                var pReadByte = r.ReadBytes((int)r.BaseStream.Length);
                return pReadByte;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);

            }
            finally
            {
                if(pFileStream ! =null) pFileStream.Close(); }}/// <summary>
        ///Writes byte to a file
        /// </summary>
        /// <param name="pReadByte">Byte stream</param>
        /// <param name="fileName">The file path</param>
        /// <returns></returns>
        public static bool WriteFile(byte[] pReadByte, string fileName)
        {
            FileStream pFileStream = null;
            try
            {
                pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
                pFileStream.Write(pReadByte, 0, pReadByte.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if(pFileStream ! =null) pFileStream.Close();
            }
            return true;

        }

        public static string ReadLine(string fileName)
        {
            if(! Exists(fileName)) {return null;
            }
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                return newStreamReader(fs).ReadLine(); }}/// <summary>
        ///Write files
        /// </summary>
        /// <param name="fileName">The file name</param>
        /// <param name="content">The file content</param>
        /// <returns></returns>
        public static bool Write(string fileName, string content)
        {
            if (Exists(fileName) || content == null)
            {
                return false;
            }
            try
            {
                // Read file information into the stream
                // Initializes a new instance of the system.io.FileStream class with the specified path and creation mode
                using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    / / lock the flow
                    lock (fs)
                    {
                        if(! fs.CanWrite) {throw new System.Security.SecurityException("The file fileName =" + fileName + "Read-only file cannot write!");
                        }

                        var buffer = Encoding.Default.GetBytes(content);
                        fs.Write(buffer, 0, buffer.Length);
                        return true;
                    }
                }
            }
            catch (IOException ioe)
            {
                throw newException(ioe.Message); }}/// <summary>
        ///Write a line
        /// </summary>
        /// <param name="fileName">The file name</param>
        /// <param name="content">content</param>
        /// <returns></returns>
        public static bool WriteLine(string fileName, string content)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException(fileName);
            if (string.IsNullOrEmpty(content))
                throw new ArgumentNullException(content);
            using (var fs = new FileStream(fileName, FileMode.OpenOrCreate | FileMode.Append))
            {
                / / lock the flow
                lock (fs)
                {
                    if(! fs.CanWrite) {throw new System.Security.SecurityException("The file fileName =" + fileName + "Read-only file cannot write!");
                    }

                    var sw = new StreamWriter(fs);
                    sw.WriteLine(content);
                    sw.Dispose();
                    sw.Close();
                    return true; }}}/// <summary>
        ///Copy directory
        /// </summary>
        /// <param name="fromDir">The directory to be copied</param>
        /// <param name="toDir">Directory to copy to</param>
        /// <returns></returns>
        public static bool CopyDir(DirectoryInfo fromDir, string toDir)
        {
            return CopyDir(fromDir, toDir, fromDir.FullName);
        }


        /// <summary>
        ///Copy directory
        /// </summary>
        /// <param name="fromDir">The directory to be copied</param>
        /// <param name="toDir">Directory to copy to</param>
        /// <returns></returns>
        public static bool CopyDir(string fromDir, string toDir)
        {
            if (fromDir == null || toDir == null)
            {
                throw new NullReferenceException("Parameter null");
            }

            if (fromDir == toDir)
            {
                throw new Exception("Both directories." + fromDir);
            }

            if(! Directory.Exists(fromDir)) {throw new IOException("Directory fromDir =" + fromDir + "Doesn't exist.");
            }

            var dir = new DirectoryInfo(fromDir);
            return CopyDir(dir, toDir, dir.FullName);
        }


        /// <summary>
        ///Copy directory
        /// </summary>
        /// <param name="fromDir">The directory to be copied</param>
        /// <param name="toDir">Directory to copy to</param>
        /// <param name="rootDir">The root directory to be copied</param>
        /// <returns></returns>
        private static bool CopyDir(DirectoryInfo fromDir, string toDir, string rootDir)
        {
            foreach (var f in fromDir.GetFiles())
            {
                var filePath = toDir + f.FullName.Substring(rootDir.Length);
                var newDir = filePath.Substring(0, filePath.LastIndexOf("\ \", StringComparison.Ordinal));
                CreateDir(newDir);
                File.Copy(f.FullName, filePath, true);
            }

            foreach (var dir in fromDir.GetDirectories())
            {
                CopyDir(dir, toDir, rootDir);
            }

            return true;
        }


        /// <summary>
        ///Delete the file
        /// </summary>
        /// <param name="fileName">The full path to the file</param>
        /// <returns></returns>
        public static bool DeleteFile(string fileName)
        {
            try
            {
                if(! Exists(fileName))return false;
                File.Delete(fileName);
            }
            catch (IOException ioe)
            {
                throw new ArgumentNullException(ioe.Message);
            }

            return true;
        }


        public static void DeleteDir(DirectoryInfo dir)
        {
            if (dir == null)
            {
                throw new NullReferenceException("Directory does not exist");
            }

            foreach (var d in dir.GetDirectories())
            {
                DeleteDir(d);
            }

            foreach (var f in dir.GetFiles())
            {
                DeleteFile(f.FullName);
            }

            dir.Delete();

        }


        /// <summary>
        ///Delete the directory
        /// </summary>
        /// <param name="dir">The specified directory</param>
        /// <param name="onlyDir">Whether to delete only directories</param>
        /// <returns></returns>
        public static bool DeleteDir(string dir, bool onlyDir)
        {
            if (dir == null || dir.Trim() == "")
            {
                throw new NullReferenceException("Directory dir =" + dir + "Doesn't exist.");
            }

            if(! Directory.Exists(dir)) {return false;
            }

            var dirInfo = new DirectoryInfo(dir);
            if (dirInfo.GetFiles().Length == 0 && dirInfo.GetDirectories().Length == 0)
            {
                Directory.Delete(dir);
                return true;
            }


            if(! onlyDir) {return false;
            }
            DeleteDir(dirInfo);
            return true;
        }


        /// <summary>
        ///Finds files in the specified directory
        /// </summary>
        /// <param name="dir">directory</param>
        /// <param name="fileName">The file name</param>
        /// <returns></returns>
        public static bool FindFile(string dir, string fileName)
        {
            if (dir == null || dir.Trim() == "" || fileName == null || fileName.Trim() == ""| |! Directory.Exists(dir)) {return false;
            }

            // Pass the file path to get the current file object
            var dirInfo = new DirectoryInfo(dir);
            return FindFile(dirInfo, fileName);

        }


        /// <summary>
        ///Returns whether the file exists
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool FindFile(DirectoryInfo dir, string fileName)
        {
            foreach (var d in dir.GetDirectories())
            {
                if (File.Exists(d.FullName + "\ \" + fileName))
                {
                    return true;
                }
                FindFile(d, fileName);
            }

            return false;
        }


        /// <summary>
        ///Gets all folder names in the specified folder
        /// </summary>
        /// <param name="folderPath">The path</param>
        /// <returns></returns>
        public static List<string> FolderName(string folderPath)
        {
            var listFolderName = new List<string> ();try
            {
                var info = new DirectoryInfo(folderPath);

                listFolderName.AddRange(info.GetDirectories().Select(nextFolder => nextFolder.Name));
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }

            return listFolderName;

        }


        /// <summary>
        ///Gets the name of the file in the specified folder
        /// </summary>
        /// <param name="folderPath">The path</param>
        /// <returns></returns>
        public static List<string> FileName(string folderPath)
        {
            var listFileName = new List<string> ();try
            {
                var info = new DirectoryInfo(folderPath);

                listFileName.AddRange(info.GetFiles().Select(nextFile => nextFile.Name));
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }

            returnlistFileName; }}Copy the code