user2047205
user2047205

Reputation: 11

Receive a file from a client and saving to a file in server in C#

What I want to do is to receive the file send from the client. But at the problem line shown below I get an exception

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\asd\Desktop\'.

This is my server code:

IPEndPoint ipEnd;
Socket sock;
byte[] clientData = new byte[1024 * 5000];
ipEnd = new IPEndPoint(IPAddress.Any, 5000);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(5000); 
Socket clientSock=sock.Accept();                
int receivedBytesLen = clientSock.Receive(clientData);
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
BinaryWriter bWrite = new BinaryWriter(File.Open(@"C:\Users\asd\Desktop\"+           fileName,FileMode.Append));//problem Line
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
bWrite.Close();
clientSock.Close();               
MessageBox.Show("recieved...");

Upvotes: 1

Views: 3842

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

I would not have your code save to the desktop you could be having permissions issues if your code is running as a different user than the desktop you specified. Change your code to the following and see if this fixes your problem

string destFolder = @"C:\ReceivedFiles"
if (Directory.Exists(destFolder) == false)
    Directory.CreateDirectory(destFolder);
BinaryWriter bWrite = new BinaryWriter(File.Open(Path.Combine(destFolder, FileName), FileMode.Append));

On to other problems with your code:

int receivedBytesLen = clientSock.Receive(clientData);

First of all, this does not guarantee that you got all of the data. If the payload is bigger than one datagram you will need to call Receive multiple times. The only way to know how many times you need to call is you need to somehow send the length of the entire binary before hand or close the connection after the file is done client side and loop building a buffer (or writing it out as it comes in) until Receive returns 0.

Secondly, you should also be using using to make sure your classes get disposed properly in the event of a exception

using(Socket clientSock=sock.Accept())
{
    //This needs to be redone, see my first point
    int receivedBytesLen = clientSock.Receive(clientData);
    int fileNameLen = BitConverter.ToInt32(clientData, 0);
    string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
    using(BinaryWriter bWrite = new BinaryWriter(File.Open(@"C:\Users\asd\Desktop\"+           fileName,FileMode.Append)))
    {
        bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
    }
}

Upvotes: 1

Related Questions