Download attachment from email - c#

How can I browse the email and download all attachments ?
public string Connect_Email ()
{
string Res = "";
try
{
mailclient = new TcpClient("pop.orange.fr", Convert.ToInt16("110"));
}
catch ( SocketException ExTrhown )
{
Res = "Unable to connect to server 1";
throw new Exception(ExTrhown.Message + "Unable to connect to server 1");
}
ns = mailclient.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
response = sr.ReadLine(); //Get opening POP3 banner
sw.WriteLine("USER " + "xxxxx#orange.fr"); //Send username
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 4) == "-ERR" )
{
Res = "Unable to log into server 2";
}
sw.WriteLine("PASS " + "xxxxx"); //Send password
sw.Flush();
response = sr.ReadLine();
if ( response.Substring(0, 3) == "-ER" )
{
Res = "Unable to log into server 3";
}
return Res;
}
public void Get_Attacht ()
{
string ClientName = "";
#region Chercher Attachment
sw.WriteLine("STAT"); //Send stat command to get number of messages
sw.Flush();
response = sr.ReadLine();
//find number of message
string[] nummess = response.Split(' ');
totmessages = Convert.ToInt16(nummess[1]);
//read emails
for ( int i = 1; i <= totmessages; i++ )
{
msg = null;
sw.WriteLine("top " + i + " 0"); //read header of each message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
//read attachment
attachment = null;
if ( Regex.Match(msg, "multipart/mixed").Success )
{
msg = null;
sw.WriteLine("retr " + i.ToString()); //Retrieve entire message
sw.Flush();
response = sr.ReadLine();
while ( true )
{
response = sr.ReadLine();
if ( response == "." )
break;
msg = msg + response + "\r\n";
}
int End = msg.IndexOf(".csv");
string LeFile = msg.Substring(End - 9, 9);
if ( Regex.Match(msg, LeFile + ".csv").Success )
{
data = msg.Split('\r');
startindex = 0;
index = 0;
lastindex = 0;
x = null;
ms = null;
fs = null;
while ( true )
{
attachment = null;
while ( !Regex.Match(data[index].Trim(), "filename").Success )
{
index++;
}
if ( index == data.Length - 1 ) break;
FileName_Email = data[index].Trim().Substring(42).Replace("\"", "");
//find start of attachment data
index++;
while ( data[index].Length != 1 )
{
index++;
}
if ( index == data.Length - 1 ) break;
startindex = index + 1;
//find end of data
index = startindex + 1;
while ( ( !Regex.Match(data[index].Trim(), "--0").Success ) && ( data[index].Length != 1 ) && ( index < data.Length - 1 ) )
{
index++;
}
if ( index == data.Length ) break;
lastindex = index - 2;
for ( int j = startindex; j <= lastindex; j++ )
{
attachment = attachment + data[j];
}
attachment = attachment + "\r\n";
if ( Regex.Match(FileName_Email.ToLower(), "csv").Success )
{
byte[] filebytes = Convert.FromBase64String(attachment);
FileStream LeFS = new FileStream(filePath + "\\testDEC.csv", FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
break;
}
}
}
}
}
sw.WriteLine("quit"); //quit
sw.Flush();
#endregion
}
It does not work, have you another simple idea ?

Try something like this
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("server");
pop3.UseBestLogin("user", "password");
foreach (string uid in pop3.GetAll())
{
IMail email = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine(email.Subject);
// save all attachments to disk
email.Attachments.ForEach(mime => mime.Save(mime.SafeFileName));
}
pop3.Close();
}
// here is a reference link you can use as well
Getting Email Attachments

If you're trying to read e-mail via POP3, I would recommend using the OpenPOP.NET library instead of rolling your own. It's pretty easy to use.

Thanks you all for your contribution. Finally I use POP3:
public string Connect_Email()
{
string Res = "";
try
{
Pop3Client email = new Pop3Client("login", "password", "server");
email.OpenInbox();
while (email.NextEmail())
{
if (email.IsMultipart)
{
IEnumerator enumerator = email.MultipartEnumerator;
while (enumerator.MoveNext())
{
Pop3Component multipart = (Pop3Component)
enumerator.Current;
if (multipart.IsBody)
{
//Console.WriteLine("Multipart body:" + multipart.Name);
}
else
{
//Console.WriteLine("Attachment name=" + multipart.Name); // ... etc
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();
}
}
}
}
email.CloseConnection();
}
catch (Pop3LoginException)
{
Res = "Vous semblez avoir un problème de connexion!";
}
return Res;
}
It work well, but still I have to find and download the attachement my self.
byte[] filebytes = Convert.FromBase64String(multipart.Data);
//Search FileName
int Begin = multipart.ContentType.IndexOf("name=");
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12);
FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None);
LeFS.Write(filebytes, 0, filebytes.Length);
LeFS.Close();

This not work more. Use Modern Authentication with Microsoft.Graph after create a cliente secret into AZURE and registered tha application them.

Related

Convert a node.js script to C#

I have this function in Node.js
let inPath = process.argv[2] || 'file.txt';
let outPath = process.argv[3] || 'result.txt';
fs.open(inPath, 'r', (errIn, fdIn) => {
fs.open(outPath, 'w', (errOut, fdOut) => {
let buffer = Buffer.alloc(1);
while (true) {
let num = fs.readSync(fdIn, buffer, 0, 1, null);
if (num === 0) break;
fs.writeSync(fdOut, Buffer.from([255-buffer[0]]), 0, 1, null);
}
});
});
What would be the equivalent in C#?
My code so far. I do not know what is the equivalent code in C# to minus byte of a character. Thank you in advanced!
var inPath = "file.txt";
var outPath = "result.txt";
string result = string.Empty;
using (StreamReader file = new StreamReader(#inPath))
{
while (!file.EndOfStream)
{
string line = file.ReadLine();
foreach (char letter in line)
{
//letter = Buffer.from([255-buffer[0]]);
result += letter;
}
}
File.WriteAllText(outPath, result);
}
var inPath = "file.txt";
var outPath = "result.txt";
//Converted
using (var fdIn = new FileStream(inPath,FileMode.Open))
{
using (var fdOut = new FileStream(outPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1];
var readCount = 0;
while (true)
{
readCount += fdIn.Read(buffer,0,1);
buffer[0] = (byte)(255 - buffer[0]);
fdOut.Write(buffer);
if (readCount == fdIn.Length)
break;
}
}
}
...
//Same code but all file loaded into memory, processed and after this saved
var input = File.ReadAllBytes(inPath);
for (int i = 0; i < input.Length; i++)
{
input[i] = (byte)(255 - input[i]);
}
File.WriteAllBytes(outPath, input);
Same code but with BinaryReader and BinaryWriter
var inPath = "file.txt";
var outPath = "result.txt";
using (BinaryReader fileIn = new BinaryReader(new StreamReader(#inPath).BaseStream))
using (BinaryWriter fileOut = new BinaryWriter(new StreamWriter(#outPath).BaseStream))
{
while (fileIn.BaseStream.Position != fileIn.BaseStream.Length)
{
var #byte = fileIn.ReadByte();
fileOut.Write((byte)(255 - #byte));
}
}

c# push notification is not working with Turkish character

I want to send notification to IOS from c#. But it does not send message contain Turkish character.
Here is my Pushmessage Function :
public bool PushMessage(string Mess, string DeviceToken, int Badge, string Custom_Field)
{
ConnectToAPNS();
List<string> Key_Value_Custom_Field = new List<string>();
String cToken = DeviceToken;
String cAlert = Mess;
int iBadge = Badge;
// Ready to create the push notification
byte[] buf = new byte[256];
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(new byte[] { 0, 0, 32 });
byte[] deviceToken = HexToData(cToken);
bw.Write(deviceToken);
bw.Write((byte)0);
// Create the APNS payload - new.caf is an audio file saved in the application bundle on the device
string msg = "";
msg = "{\"aps\":{\"alert\":\"" + cAlert + "\",\"badge\":\"" + iBadge.ToString() + "\",\"sound\":\"noti.aiff\",\"priority\":\"10\"}";
String PayloadMess = "";
if (string.IsNullOrWhiteSpace(Custom_Field) == false)
{
List<string> list_Custom_Field = Custom_Field.Split(';').ToList();
if (list_Custom_Field.Count > 0)
{
for (int indx = 0; indx < list_Custom_Field.Count; indx++)
{
Key_Value_Custom_Field = list_Custom_Field[indx].Split('=').ToList();
if (Key_Value_Custom_Field.Count > 1)
{
if (PayloadMess != "") PayloadMess += ", ";
PayloadMess += "\"" + Key_Value_Custom_Field[0].ToString() + "\":\"" + Key_Value_Custom_Field[1].ToString() + "\"";
}
}
}
}
if (PayloadMess != "")
{
msg += ", " + PayloadMess;
}
msg += "}";
bw.Write((byte)0);
bw.Write((byte)msg.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg);
bw.Write(b1);
bw.Flush();
if (sslStream != null)
{
sslStream.Write(ms.ToArray());
return true;
}
return false;
}
Here is the solution:
I change
bw.Write((byte)msg.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(msg);
bw.Write(b1);
to
byte[] bytes = Encoding.UTF8.GetBytes(msg);
// Write the data out to the stream
bw.Write((byte)bytes.Length);
bw.Write(msg.ToCharArray());
Now it works.The problem is character count was wrong.
Probably you just used
Encoding.UTF8.GetBytes(Message);
You can try the following:
Encoding iso = Encoding.GetEncoding("ISO-8859-9"); //Turkish
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

Uri encoding, file download doesn't work with , and whitespace

I have an asp.net webpage that allows downloading files.
When i had the problem of downloading a file with whitespace(Test 1 4 3.txt) it will turn the file into: Test+1+4+3.txt
I used:
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
And it solved the issue.
Now i have a new issue:
When a file contains , it changes it into %2c and i the UrlEncode doesn't fix it.
i Tried using:
_Response.AddHeader("Content-Disposition", "attachment;filename=" + Uri.EscapeDataString(_fileName));
But it's the old setting and it doesn't support whitespace.
What can i do to solve such a case?
Should i use regex / switch?
This is my function:
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed = 1024000)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
//Old didn't work with both + and ,
//_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
_Response.AddHeader("Content-Disposition", "attachment;filename=" + Uri.EscapeDataString(_fileName));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
This solved it:
_Response.AddHeader("Content-Disposition", "attachment;filename=\"" + _fileName + "\"");

tcpclient reads fewer bytes than expected

I have a problem with tcpclient, I need to send one or more files, so I have an application with server and client, the protocol is this :
1) I send some strings with information about number of files, files name and their sizes, all this with streamwriter.writeline (received from server with the function
streamreader.readline)
2) After these strings I send the files, after each file the server answers to the client with a streamwriter.writeline of "ACK". The file is sent with the
networkstream.write method, and received with networkstream.read.
The problem is that the server reads till the received bytes are equal to the file size, but... despite the client "seems" to send every byte of the file, the server
receives fewer bytes in total! So the application is blocked in this step, the server is waiting for the next bytes and the client is waiting for the string of "ACK"
with the streamreader.readline before to send the next file or just to finish the operation.
I also wanted to check what the server receives, so I print the number of bytes received during the reading cycle , discovering that sometimes the server reads fewer bytes than the buffer size of the stream (fixed to 1024). This should be normal because TCP reads as soon as it can, it should not be the real problem, right? I can't
believe that tcp loses bytes, but I don't know how to resolve.
Here you can find some part of codes :
----SERVER SIDE----------
..........Doing Stuffs.............
//secServer is the TCPListener socket.
this.secSHandler = secServer.AcceptTcpClient();
this.secSHandler.ReceiveBufferSize = 1024;
this.secSHandler.SendBufferSize = 1024;
this.is_connected_now = true;
print("is connected!!! ");
//Taking streams...
this.stream = this.secSHandler.GetStream();
this.sr = new StreamReader(stream);
this.sw = new StreamWriter(stream);
string first = sr.ReadLine();
print("I read + " + first + " .");
int numFiles = 0;
string connType = first.Substring(0, 6);
if (connType.CompareTo("CLIENT") == 0)
{
//SINCR CLIENT -> SERVER
string clipType = first.Substring(7, 4);
if (clipType.CompareTo("FILE") == 0)
{
//CASE RECEIVE FILE
int posSeparator = first.IndexOf('*');
string nFiles = first.Substring(12, first.Length - 13);
numFiles = Convert.ToInt16(nFiles);
string[] fileNames = new string[numFiles];
int[] fileSizes = new int[numFiles];
//TAKE FROM THE CLIENT ALL FILE NAMES AND SIZES
for (int i = 0; i < numFiles; i++)
{
fileNames[i] = sr.ReadLine();
print("Name file : I read " + fileNames[i]);
string dim = sr.ReadLine();
fileSizes[i] = Convert.ToInt32(dim);
print("Size file : I read " + fileSizes[i]);
}
//RECEVING FILES
for (int i = 0; i < numFiles; i++)
{
receive_single_file_1(stream, fileSizes[i], fileNames[i]); //CANNOT GO AFTER THIS POINT
sw.WriteLine("File sent - number " + i);
sw.Flush();
}
}
}
.............Doing others stuffs.............
sr.Close();
sw.Close();
THE FUNCTION RECEIVE SINGLE FILE IS HERE BELOW
public bool receive_single_file_1(NetworkStream netstream, int size, string filename)
{
int sizeToRead = 0;
string f_name = "";
//...f_name is the result of another operation, for the sake of the example i write only the final instruction
f_name = filename;
byte[] RecData = new byte[1024];
int RecBytes = 0;
try
{
int totalrecbytes = 0;
FileStream Fs = new FileStream((tempFold + f_name), FileMode.OpenOrCreate, FileAccess.Write);
//COUNTER OF THE WHILE
int nciclo = 0;
while ((RecBytes = netstream.Read(RecData, 0, 1024)) > 0)
{
//I defined print in another context...
totalrecbytes += RecBytes;
if(RecBytes!=1024)
print("Cycle : "+ nciclo +" Content RecBytes : " + RecBytes + " e RecData.Length : " + RecData.Length + " byte reads : " + totalrecbytes + ".");
Fs.Write(RecData, 0, RecBytes);
if (totalrecbytes >= size)
{
print("Read all bytes " + totalrecbytes + " over " + size + " .");
break;
}
//Refresh the buffer
RecData = new byte[1024];
nciclo++;
}
print("End of transfer. Received " + totalrecbytes + "File :" + filename + " Saved on " + tempFold);
Fs.Close();
}
catch (Exception ex)
{
//Ok here i return false, but i do some other stuff before
return false;
}
return true;
}
----END OF SERVER SIDE--------------
--------CLIENT SIDE--------------
.....DOING STUFFS....
//sw is the streamWriter, Sr the streamReader and the stream is the networkstream
System.Collections.Specialized.StringCollection formats = Clipboard.GetFileDropList();
sw.WriteLine("CLIENT:FILE:" + formats.Count + "*");
sw.Flush();
//Sending to the server filename and relative size
foreach (string filename in formats)
{
//Ok the * has sense in my protocol...ignore it.
sw.WriteLine((Directory.Exists(filename)) ? System.IO.Path.GetFileName(filename) + "*" : System.IO.Path.GetFileName(filename));
sw.Flush();
FileStream Fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
sw.WriteLine(Fs.Length);
sw.Flush();
stream.Flush();
Fs.Close();
}
//Sending files
foreach (string filename in formats)
{
//client_sync is the class that wrap the TcpClient socket
client_sync.send_single_file(stream, filename);
resp = sr.ReadLine();
}
....DOING STUFF AND end of this function...
The send file function is defined in this way :
(note : i take this function from code project some weeks ago)
public void send_single_file(NetworkStream netstream, string filename)
{
//connected is a param of my class
if (!connected) return;
byte[] SendingBuffer = null;
try
{
FileStream Fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(this.BufferSize)));
//NOTE: BUFFERSIZE IS 1024
int TotalLength = (int)Fs.Length, CurrentPacketLength = 0;
int bytes_send = 0;
for (int i = 0; i < NoOfPackets; i++)
{
if (TotalLength > this.BufferSize)
{
CurrentPacketLength = this.BufferSize;
TotalLength = TotalLength - CurrentPacketLength;
}
else
CurrentPacketLength = TotalLength;
SendingBuffer = new byte[CurrentPacketLength];
Fs.Read(SendingBuffer, 0, CurrentPacketLength);
netstream.Write(SendingBuffer, 0, SendingBuffer.Length);
bytes_send += CurrentPacketLength;
}
Fs.Close();
}
catch (Exception ex)
{
netstream.Close();
//my function
close_connection();
}
netstream.Flush();
}
---------END OF CLIENT SIDE------
So...someone can help me to escape from this hell??? THX :)

Socket.Receive() returns incorrect amount of data

As school project I'm creating a FileSharing application.
I send all the messages I want to the server and everything is fine, but when it comes to Upload a file to the server, the file is never the way it should be. I debugged the application and discovered that the Socket is not returning the correct amount of bytes.
I don't know if that's the correct way it should be, but I thinks it's wrong.
For example when I upload a small .txt file, and open it with Notepad++ I see a lot of null's at the end of the file, wich means that I'm writting more then it should be written. I searched it on the internet and found an application at codeplex that does the same that I'm doing, but the socket returns the correct amount of data, http://srf.codeplex.com/.
I would appreciate if someone could help me.
Sorry if english sucks, its not my native language.
Server function that handles first message and does receives the clint connection:
public void Brodcast()
{
tcpListener.Start();
while (true)
{
try
{
ClientSocket = tcpListener.AcceptSocket();
MessageReceiving();
}
catch { }
}
}
public void MessageReceiving()
{
if (ClientSocket.Connected)
{
OpenPackage.MessageTypeToBytes RSMessage = new OpenPackage.MessageTypeToBytes();
ClientSocket.Receive(RSMessage.MessageBytes, 512, SocketFlags.None);
if (RSMessage.TypeOfMessage == MessageType.Login)
DoLogin();
else if (RSMessage.TypeOfMessage == MessageType.Download)
SendFile();
else if (RSMessage.TypeOfMessage == MessageType.Upload)
ReceiveFile();
else if (RSMessage.TypeOfMessage == MessageType.NConta)
NewAccount();
else if (RSMessage.TypeOfMessage == MessageType.Search)
SearchResult();
else if (RSMessage.TypeOfMessage == MessageType.Apagar)
DeleteFile();
}
}
Server:
public void ReceiveFile()
{
try
{
byte[] MessageBytes = new byte[512];
ClientSocket.Receive(MessageBytes, 512, SocketFlags.None);
string Nickname = Encoding.ASCII.GetString(MessageBytes);
string[] CNickFich = Nickname.Split('$');
FileHandler Handler = new FileHandler();
long DirectorySize = Handler.GetDirectorySize("C:\\" + CNickFich[0]);
long FileSize = long.Parse(CNickFich[2]);
bool Subs = false;
if ((FileSize + DirectorySize) < MaxFolderSize && MaxFileSize > FileSize)
{
if (!Directory.Exists("C:\\" + CNickFich[0]))
Directory.CreateDirectory("C:\\" + CNickFich[0]);
if (File.Exists("C:\\" + CNickFich[0] + "\\" + CNickFich[1]))
{
File.Delete("C:\\" + CNickFich[0] + "\\" + CNickFich[1]);
Subs = true;
}
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.OK };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
int qtdReceived = 0;
long CurrentSize = 0;
byte[] FileBuffer = new byte[BufferSize];
FileStream FileStr = new FileStream("C:\\" + CNickFich[0] + "\\" + CNickFich[1], FileMode.CreateNew, FileAccess.Write);
BufferedStream BufferStr = new BufferedStream(FileStr);
while (CurrentSize < FileSize)
{
qtdReceived = ClientSocket.Receive(FileBuffer, 0, FileBuffer.Length, 0);
CurrentSize += qtdReceived;
BufferStr.Write(FileBuffer, 0, qtdReceived);
BufferStr.Flush();
}
BufferStr.Close();
FileStr.Close();
SqlDataAdapter data = new SqlDataAdapter("SELECT COD_CONTA FROM CONTAS WHERE NICKNAME='"
+ CNickFich[0] + "'", OConn);
DataTable dt = new DataTable();
data.Fill(dt);
if (NFicheiro(Handler.MD5HashFromFile("C:\\" + CNickFich[0] + "\\" + CNickFich[1]), "C:\\" + CNickFich[0] + "\\" + CNickFich[1], Subs,
int.Parse(dt.Rows[0][0].ToString()), CNickFich[3]))
MessageInBytes.TypeOfMessage = MessageType.OK;
else
MessageInBytes.TypeOfMessage = MessageType.Erro;
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
//NFicheiro(new FileHandler().MD5HashFromFile("C:\\" + CNickFich[0] + "\\" + CNickFich[1]), "C:\\" + CNickFich[0], false, 1, );
}
else
{
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
}
}
catch
{
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
}
}
Client:
private void UploadWork_DoWork(object sender, DoWorkEventArgs e)
{
FileStream FileStr = null;
BufferedStream BufferStr = null;
Stopwatch Counter = new Stopwatch();
try
{
int CurrentProgress = 0;
Program.CTasks.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Program.CTasks.ClientSocket.ReceiveTimeout = 60000;
Program.CTasks.ClientSocket.SendTimeout = 60000;
Program.CTasks.ClientSocket.Connect(IPAddress.Parse(Program.CTasks.HostName), Program.CTasks.Port);
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Upload };
Program.CTasks.ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
FileInfo FileNFO = new FileInfo(Open.FileName);
byte[] NickPath = new byte[512];
byte[] UNickPath = Encoding.ASCII.GetBytes(Program.Nickname + "$" + Open.FileName.Substring(Open.FileName.LastIndexOf('\\') + 1) + "$" + FileNFO.Length.ToString() + "$");
byte[] TagCollectionBytes = Encoding.ASCII.GetBytes(TagCollection + "$");
UNickPath.CopyTo(NickPath, 0);
TagCollectionBytes.CopyTo(NickPath, UNickPath.Length);
Program.CTasks.ClientSocket.Send(NickPath, 512, SocketFlags.None);
Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
if (MessageInBytes.TypeOfMessage == MessageType.OK)
{
long FileSize = FileNFO.Length;
long CurrentFileSize = 0;
long qtdRead = 0;
byte[] FileBytes = new byte[BufferSizer];
FileStr = new FileStream(Open.FileName, FileMode.Open, FileAccess.Read);
BufferStr = new BufferedStream(FileStr);
Counter.Start();
while ((qtdRead = BufferStr.Read(FileBytes, 0, FileBytes.Length)) > 0)
{
Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
CurrentFileSize += qtdRead;
CurrentProgress = (int)((CurrentFileSize * 100) / FileSize);
UploadSpeed = ((double)CurrentFileSize / (Counter.Elapsed.TotalMilliseconds / 100));
UploadWork.ReportProgress(CurrentProgress);
}
FileStr.Close();
Counter.Stop();
Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
Program.CTasks.ClientSocket.Close();
}
}
catch
{
try
{
Counter.Stop();
FileStr.Close();
Program.CTasks.ClientSocket.Close();
}
catch { }
}
}
You're sending too much data... at the end of the file FileBytes will on longer be completely full, and you should only send qtdRead bytes.
Replace
Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
With
Program.CTasks.ClientSocket.Send(FileBytes, 0, qtdRead, 0);
You are using your buffer length rather than the length of what you read when sending.

Categories

Resources