पढ़ रहा Filestream उपयोग कर रहा हूँ के लिए बड़ी फ़ाइल (> 500 एमबी) पढ़ सकते हैं और मैं OutOfMemoryException मिलता है।OutOfMemoryException जब मैं 500MB FileStream
इसके बारे में कोई समाधान।
मेरे कोड है:
using (var fs3 = new FileStream(filePath2, FileMode.Open, FileAccess.Read))
{
byte[] b2 = ReadFully(fs3, 1024);
}
public static byte[] ReadFully(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
कृपया, जो सबसे अच्छा कोड है, मैं इस का उपयोग करते हुए: http://www.yoda.arachsys.com/csharp/readbinary.html धन्यवाद श्रीमान –
+1: हाँ, बफर आकार आप की जरूरत का आवंटन एक है अच्छा विचार ... वास्तव में, मुझे हैरान है कि .NET में एक संपूर्ण फ़ाइल को बाइट सरणी या किसी अन्य समान संरचना में पढ़ने का कोई तरीका नहीं है। – Powerlord
यह करता है। File.ReadAllBytes http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx लेकिन ऐसा नहीं है कि यह पोस्टर क्या कर रहा है। स्मृति में 500 एमबी फ़ाइल के सभी बाइट्स को पढ़ना * आमतौर पर एक बुरा विचार * है, और इस मामले में ... यह एक बहुत बुरा विचार है। पोस्टर स्पष्ट रूप से एक प्राथमिक, अभी तक अस्थिर लक्ष्य को ध्यान में रखता है जो "फ़ाइल में सभी बाइट्स को स्मृति में नहीं पढ़ता है।" वह * सोचता है * उसे सभी बाइट्स पढ़ने की जरूरत है, लेकिन यह सच नहीं है। – Cheeso