Question

my code is:

byte[] buffer = new byte[1024];
int numberOfBytesRead = 0;
MemoryStream receivedData = new MemoryStream();
do
{
numberOfBytesRead = serverStream.Read(buffer, 0, buffer.Length); //Read from network stream
receivedData.Write(buffer, 0, numberOfBytesRead); //Write to memory stream
Thread.Sleep(1);
} while (serverStream.DataAvailable);
File.WriteAllBytes(@"C:\file.png", receivedData.ToArray());

I want convert it from MemoryStream to FileStream and i don't know.

and why i must use Thread.Sleep(1) to complete receiving bytes of file. Is there any correct statement instead of Sleep.

very thanks

Était-ce utile?

La solution

Code using FileStream :

    byte[] buffer = new byte[1024];
    int numberOfBytesRead = 0;

    FileStream fs = new FileStream(@"C:\file.png", FileMode.Create, FileAccess.Write);
    do
    {
        numberOfBytesRead = serverStream.Read(buffer, 0, buffer.Length); //Read from network stream
        fs.Write(buffer, 0, numberOfBytesRead);
    } while (serverStream.DataAvailable);
    fs.Close();

Autres conseils

The conversion is very simple, and I am assuming that you are having trouble with how to open the file. The File class provides a lot of useful utility methods in addition to the last one that you use, like File.OpenWrite:

FileStream receivedData = File.OpenWrite(@"C:\file.png");

As for the Thread.Sleep(1)--unless I am missing something not shown here--it looks like a chance to let the processor rest but it's rather pointless. In particular, the Read call is IO bound waiting on the socket (network) to provide input so the entire loop is unlikely to be worthy of needing to sleep. Most calls to Thread.Sleep are hackish in nature.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top