C# 创建指定大小文件 C#读取大文件

      //  
        /// 创建固定大小的临时文件 
        ///  
        /// 文件名  
        /// 文件大小  
        /// 允许覆写:可以覆盖掉已经存在的文件  
        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();
            }
        }
        ///
        /// 读取大文件用,读取文件前面指定长度字节数
        ///
        /// 文件路径
        /// 读取长度,单位字节
        ///
        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) //如果需要转换成编码字符串的话
        }
        ///
        /// 普通文件读取方法
        ///
        ///
        ///
        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;
        }

你可能感兴趣的:(C#,c#)