sockets - Receive a file from a client and saving to a file in server in C# -
what want receive file send client. @ problem line shown below exception
system.io.directorynotfoundexception: not find part of path 'c:\users\asd\desktop\'.
this 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...");
i not have code save desktop having permissions issues if code running different user desktop specified. alter code next , see if fixes 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 other problems code:
int receivedbyteslen = clientsock.receive(clientdata);
first of all, this not guarantee got of data. if payload bigger 1 datagram need phone call receive
multiple times. way know how many times need phone call need somehow send length of entire binary before hand or close connection after file done client side , loop building buffer (or writing out comes in) until receive returns 0.
secondly, should using using
create sure classes disposed in event of exception
using(socket clientsock=sock.accept()) { //this needs redone, see 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); } }
c# sockets file-transfer
No comments:
Post a Comment