c# - Cast filestream length to int -


i have question safety of cast long int. fear method wrote might fail @ cast. can please take @ code below , tell me if possible write avoid possible fail?

thank in advance.

    public static string readdecrypted(string filefullpath)     {         string result = string.empty;          using (filestream fs = new filestream(filefullpath, filemode.open, fileaccess.read))         {             int fslength = (int)fs.length;             byte[] decrypted;             byte[] read = new byte[fslength];             if (fs.canread)             {                 fs.read(read, 0, fslength);                 decrypted = protecteddata.unprotect(read, createentropy(), dataprotectionscope.currentuser);                 result = utils.appdefaultencoding.getstring(decrypted, 0, decrypted.length);             }         }         return result;     } 

the short answer is: yes, way have problems file length >= 2 gb!

if don't expect files big can insert directly @ start of using block:

if (((int)fs.length) != fs.length) throw new exception ("too big"); 

otherwise should not cast int, change byte[] read = new byte[fslength]; byte[] read = new byte[fs.length]; , use loop read file content in "chunks" of max. 2 gb per chunk.

another alternative (available in .net4) use memorymappedfile (see http://msdn.microsoft.com/en-us/library/dd997372.aspx) - way don't need call read @ :-)


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -