------------恢复内容开始------------

        /// <summary> 
        /// 创建固定大小的临时文件 
        /// </summary> 
        /// <param name="fileName">文件名</param> 
        /// <param name="fileSize">文件大小</param> 
        /// <param name="overwrite">允许覆写:可以覆盖掉已经存在的文件</param> 
        public static void CreateFixedSizeFile(string fileName, long fileSize)
        {
            //验证参数 
            if (string.IsNullOrEmpty(fileName) || new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Contains(
                    fileName[fileName.Length - 1]))
                throw new ArgumentException("fileName");
            if (fileSize < 0) throw new ArgumentException("fileSize");
            //创建目录 
            string dir = Path.GetDirectoryName(fileName);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            //创建文件 
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Create);
                fs.SetLength(fileSize); //设置文件大小 
            }
            catch
            {
                if (fs != null)
                {
                    fs.Close();
                    File.Delete(fileName); //注意,若由fs.SetLength方法产生了异常,同样会执行删除命令,请慎用overwrite:true参数,或者修改删除文件代码。 
                }
                throw;
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }


        /// <summary>
        /// 读取大文件用,读取文件前面指定长度字节数
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="readByteLength">读取长度,单位字节</param>
        /// <returns></returns>
        public byte[] ReadBigFile(string filePath,int readByteLength)
        { 
            FileStream stream = new FileStream(filePath,FileMode.Open);
            byte[] buffer = new byte[readByteLength];
            stream.Read(buffer, 0, readByteLength);
            stream.Close();
            stream.Dispose();
            return buffer;
            //string str = Encoding.Default.GetString(buffer) //如果需要转换成编码字符串的话
        }
        /// <summary>
        /// 普通文件读取方法
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string ReaderFile(string path)
        {
            string fileData = string.Empty;
            ///读取文件的内容     
            StreamReader reader = new StreamReader(path, Encoding.Default);
            fileData = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            return fileData;
        }

————————————————
版权声明:本文为CSDN博主「绀目澄清」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u013628121/article/details/52577702

 kkkkkkkk

------------恢复内容结束------------

01-03 11:16