示例#1
0
 /// <summary>
 ///     Writes content to file
 /// </summary>
 /// <param name="r"> </param>
 /// <param name="name"> </param>
 /// <param name="content"> </param>
 /// <param name="userLog"> </param>
 /// <param name="append"> </param>
 /// <returns> </returns>
 public static IFileNameResolver Write(this IFileNameResolver r, string name, object content,
                                       IUserLog userLog = null, bool append = false)
 {
     if (r == null)
     {
         throw new ArgumentNullException("r");
     }
     lock (writelock) {
         userLog = checkUserLog(r, userLog);
         userLog.Debug("start write " + name);
         var path = r.Resolve(name, false, null, userLog);
         userLog.Debug("path resolved as " + path);
         Directory.CreateDirectory(Path.GetDirectoryName(path));
         if (append)
         {
             appendFile(path, content);
         }
         else
         {
             rewriteFile(path, content);
         }
         r.ClearCache();
         userLog.Trace("file saved " + path);
         return(r);
     }
 }
示例#2
0
        /// <summary>
        ///     Read content of file
        /// </summary>
        /// <param name="r"> </param>
        /// <param name="name"> </param>
        /// <param name="userLog"> </param>
        /// <typeparam name="T"> </typeparam>
        /// <returns> </returns>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static T Read <T>(this IFileNameResolver r, string name, IUserLog userLog = null)
        {
            if (r == null)
            {
                throw new ArgumentNullException("r");
            }
            if (typeof(T) == typeof(string) || typeof(T) == typeof(XElement) || typeof(T) == typeof(byte[]))
            {
                userLog = checkUserLog(r, userLog);
                userLog.Debug("start write " + name);
                var path = r.Resolve(name, true, null, userLog);

                if (null == path)
                {
                    userLog.Error("file not found");
                    throw new FileNotFoundException(name);
                }
                userLog.Debug("path resolved as " + path);
                object result = default(T);
                if (typeof(T) == typeof(string))
                {
                    result = File.ReadAllText(path);
                }
                else if (typeof(T) == typeof(byte))
                {
                    result = File.ReadAllBytes(path);
                }
                else if (typeof(T) == typeof(XElement))
                {
                    result = XElement.Load(path);
                }
                userLog.Trace("file readed " + path);
                return((T)result);
            }
            throw new ArgumentException("Read method supports only strings, XElement and byte[] as result");
        }