示例#1
0
 /// <summary>
 /// Read all the text of a file in one go, same as File.ReadAllText expect it's truly a read only function
 /// </summary>
 public static string ReadAllText(string path, Encoding encoding = null)
 {
     try {
         using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
             using (var textReader = new StreamReader(fileStream, encoding ?? TextEncodingDetect.GetFileEncoding(path))) {
                 return(textReader.ReadToEnd());
             }
         }
     } catch (Exception e) {
         throw new Exception($"Can not read the file {path.PrettyQuote()}.", e);
     }
 }
示例#2
0
        /// <summary>
        ///     Reads all the line of either the filePath (if the file exists) or from byte array dataResources,
        ///     Apply the action toApplyOnEachLine to each line
        ///     Uses encoding as the Encoding to read the file or convert the byte array to a string
        ///     Uses the char # as a comment in the file
        /// </summary>
        public static bool ForEachLine(string filePath, byte[] dataResources, Action <int, string> toApplyOnEachLine, Encoding encoding = null, Action <Exception> onException = null)
        {
            encoding = encoding ?? TextEncodingDetect.GetFileEncoding(filePath);
            var wentOk = true;

            try {
                SubForEachLine(filePath, dataResources, toApplyOnEachLine, encoding);
            } catch (Exception e) {
                wentOk = false;
                onException?.Invoke(e);

                // read default file, if it fails then we can't do much but to throw an exception anyway...
                if (dataResources != null)
                {
                    SubForEachLine(null, dataResources, toApplyOnEachLine, encoding);
                }
            }

            return(wentOk);
        }