Character Limit in filepath C# - c#

I have the following piece of code which uploads a file and checks its validity.
First issue:
if (RadUpload1.UploadedFiles.Count == 0)
{
Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
ErrorsList.ERR_P_DATE_FILE_VALID);
}
else
{
if (RadUpload1.UploadedFiles.Count > 0)
{
foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
{
FileInfo fi = new FileInfo(validFile.FileName);
Stream fs = validFile.InputStream;
IDbContextualRecord pFile = statusContext.CreateAndAddRecordForInsert(PartStoredFile.t_name);
pFile[PartStoredFile.c_partId] = _part[Part.c_id];
string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] +
"\\partRec\\" + _part[Part.c_id] + "\\" + pFile[PartStoredFile.c_id];
long bytesOnTheStream = 0L;
try
{
DirectoryInfo dir = new DirectoryInfo(targetFolder);
if (dir.Exists == false)
dir.Create();
string fullFileName = Path.Combine(targetFolder, fi.Name);
Stream targetStream = File.OpenWrite(fullFileName);
byte[] buffer = new Byte[AppConstants.BUFF_SIZE];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0)
{
targetStream.Write(buffer, 0, bytesRead);
bytesOnTheStream += bytesRead;
}
fs.Close();
targetStream.Close();
}
catch (Exception ex)
{
throw ex;
}
What I want to do is to check if the number of characters in the filepath name exceeds 260 to display me a message of error.
This is the second issue after the modification was made:
if (RadUpload1.UploadedFiles.Count <= 0)
{
Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
ErrorsList.ERR_P_DATE_FILE_VALID);
}
else
{
if (RadUpload1.UploadedFiles.Count > 0 )
{
foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
{
pomDoc = (IDbContextualRecord)Session[AppConstants.POM_DOCUMENT_NEW];
FileInfo fi = new FileInfo(validFile.FileName);
Stream fs = validFile.InputStream;
IDbContextualRecord pomFile = pomContext.CreateAndAddRecordForInsert(PomFile.t_name);
pomFile[PomFile.c_pomDocumentId] = pomDoc[PomDocument.c_id];
string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] + "\\POM\\" + pomDoc[PomDocument.c_id] + "\\" + pomFile[PomFile.c_id];
long bytesOnTheStream = 0L;
try
{
DirectoryInfo dir = new DirectoryInfo(targetFolder);
if (dir.Exists == false)
dir.Create();
string fullFileName = Path.Combine(targetFolder, fi.Name);
if (fullFileName.Length > 260)
{
throw new Exception(string.Format("The filename is too long!",fullFileName));
}
Stream targetStream = File.OpenWrite(fullFileName);
byte[] buffer = new Byte[AppConstants.BUFF_SIZE];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0)
{
targetStream.Write(buffer, 0, bytesRead);
bytesOnTheStream += bytesRead;
}
fs.Close();
targetStream.Close();
}
catch (Exception ex)
{
throw ;
}

You just have to compare fullFileName.Lenght to 260 and raise an exception if needed:
if (RadUpload1.UploadedFiles.Count <= 0) // Changed the condition to remove the check within the else block
{
Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
ErrorsList.ERR_P_DATE_FILE_VALID);
}
else
{
foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
{
FileInfo fi = new FileInfo(validFile.FileName);
Stream fs = validFile.InputStream;
IDbContextualRecord pFile = statusContext.CreateAndAddRecordForInsert(PartStoredFile.t_name);
pFile[PartStoredFile.c_partId] = _part[Part.c_id];
string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] +
"\\partRec\\" + _part[Part.c_id] + "\\" + pFile[PartStoredFile.c_id];
long bytesOnTheStream = 0L;
try
{
DirectoryInfo dir = new DirectoryInfo(targetFolder);
if (dir.Exists == false)
dir.Create();
string fullFileName = Path.Combine(targetFolder, fi.Name);
if(fullFileName.Length > 260)
{
throw new Exception(string.Format("The filename {0} is too long.", fullFileName));
// Or do whatever you want
}
Stream targetStream = File.OpenWrite(fullFileName);
byte[] buffer = new Byte[AppConstants.BUFF_SIZE];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0)
{
targetStream.Write(buffer, 0, bytesRead);
bytesOnTheStream += bytesRead;
}
fs.Close();
targetStream.Close();
}
catch (Exception ex)
{
throw;
}
Also, you don't want to throw ex; but rather throw; or this will reset the stacktrace, see Is there a difference between "throw" and "throw ex"?

Related

How to download very large files (~50 GB) from FTP Server using ftpwebrequest in C#

I've tried downloading file from FTP server in chunks using the FtpWebRequest and merging the chunks to original file. The process works fine for 4GB or lower files but when trying the same process for 8 or 9GB files I'm getting an error
Here is the error I'm getting
Here is the sample code I've worked out
private static long limitSize = Convert.ToInt64(ConfigurationManager.AppSettings["LimitSize"]);
public static void DownloadFromFTP()
{
var guid = Guid.NewGuid().ToString();
var path = $"{System.Environment.CurrentDirectory}/UploadedFiles/{guid}";
try
{
string strFilePath = ConfigurationManager.AppSettings["FilePath"];
NetworkCredential credentials = new NetworkCredential(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"]);
Console.WriteLine("Starting...");
string name = ConfigurationManager.AppSettings["FileName"];
var strFolderPath = ConfigurationManager.AppSettings["Key"] + name;
FtpWebRequest sizeRequest = (FtpWebRequest)WebRequest.Create(strFilePath);
sizeRequest.KeepAlive = false;
sizeRequest.Credentials = credentials;
sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;
long size = sizeRequest.GetResponse().ContentLength;
Console.WriteLine($"File has {size} bytes");
double filesizecheck = Convert.ToDouble(size) / Convert.ToDouble(limitSize);
int chunks = Convert.ToInt32(Math.Ceiling(filesizecheck));
long chunkLength = size / chunks;
List<Task> tasks = new List<Task>();
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
var filepath = $"{path}/{name}";
for (int chunk = 0; chunk < chunks; chunk++)
{
int i = chunk;
tasks.Add(Task.Run(() =>
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(strFilePath);
request.Credentials = credentials;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false;
request.ContentOffset = chunkLength * i;
long toread =
(i < chunks - 1) ? chunkLength : size - request.ContentOffset;
Console.WriteLine(
$"Downloading chunk {i + 1}/{chunks} with {toread} bytes ...");
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(filepath + "." + i))
{
var bufferSize = Convert.ToInt32(ConfigurationManager.AppSettings["BufferSize"]);
byte[] buffer = new byte[bufferSize];
int read;
while (((read = (int)Math.Min(buffer.Length, toread)) > 0) &&
((read = ftpStream.Read(buffer, 0, read)) > 0))
{
fileStream.Write(buffer, 0, read);
toread -= read;
}
}
Console.WriteLine($"Downloaded chunk {i + 1}/{chunks}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
Console.ReadKey();
}
}));
}
Console.WriteLine("Started all chunks downloads, waiting for them to complete...");
Task.WaitAll(tasks.ToArray());
CombineMultipleFilesIntoSingleFile(path, filepath);
var result = UploadToS3(filepath, strFolderPath, size, path).Result;
Console.WriteLine("Done");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex.Message);
DeleteFiles(path);
Console.ReadKey();
}
Console.ReadKey();
Console.ReadKey();
}
Here is the method to merge the files
private static void CombineMultipleFilesIntoSingleFile(string inputDirectoryPath, string outputFilePath)
{
string[] inputFilePaths = Directory.GetFiles(inputDirectoryPath);
Console.WriteLine("Number of files: {0}.", inputFilePaths.Length);
using (var outputStream = File.Create(outputFilePath))
{
foreach (var inputFilePath in inputFilePaths)
{
using (var inputStream = File.OpenRead(inputFilePath))
{
// Buffer size can be passed as the second argument.
inputStream.CopyTo(outputStream);
}
Console.WriteLine("The file {0} has been processed.", inputFilePath);
}
}
}
App Config settings
<add key="LimitSize" value="10000000"/>
<add key="BufferSize" value="10240"/>

Unzip files in Windows Phone 8 - 'System.OutOfMemoryException'

I used the UnZipper class from this (How to unzip files in Windows Phone 8) post in my app for zips with images, but in some rare cases it gives me this error:
A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.Windows.Application.GetResourceStreamInternal(StreamResourceInfo zipPackageStreamResourceInfo, Uri resourceUri) at System.Windows.Application.GetResourceStream(StreamResourceInfo zipPackageStreamResourceInfo, Uri uriResource) at ImperiaOnline.Plugins.UnZipper.GetFileStream(String filename) at ImperiaOnline.Plugins.IOHelpers.unzip(String zipFilePath, String zipDestinationPath)
The device has more then twice needed free memory. Can somebody help me with this. Here is my code:
public static void unzip(string zipFilePath,string zipDestinationPath) {
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var dirNames = isolatedStorage.GetDirectoryNames(zipDestinationPath);
bool doesFolderExists = (dirNames.Length > 0) ? true : false;
if (!doesFolderExists)
{
Debug.WriteLine("Folder does not exists");
isolatedStorage.CreateDirectory(zipDestinationPath);
}
try
{
using (IsolatedStorageFileStream zipFile = isolatedStorage.OpenFile(zipFilePath, FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(zipFile);
bool isModuleFolderDeleted = false;
foreach (string currentFileAndDirectory in unzip.FileNamesInZip())
{
string[] fileLocations = currentFileAndDirectory.Split('/');
string prefix = zipDestinationPath + '/';
int locationsCount = fileLocations.Length;
string fileName = fileLocations.Last();
string currentPath = prefix;
for (int i = 0; i < locationsCount - 1; i++)
{
dirNames = isolatedStorage.GetDirectoryNames(currentPath + fileLocations[i]);
doesFolderExists = (dirNames.Length > 0) ? true : false;
if (!doesFolderExists)
{
isolatedStorage.CreateDirectory(currentPath + fileLocations[i]);
if (i == 2)
{
isModuleFolderDeleted = true;
}
}
else if (i == 2 && !isModuleFolderDeleted)
{
Debug.WriteLine(currentPath + fileLocations[i] + " is deleted and recreated");
DeleteDirectoryRecursively(isolatedStorage, currentPath + fileLocations[i]);
isolatedStorage.CreateDirectory(currentPath + fileLocations[i]);
isModuleFolderDeleted = true;
}
currentPath += fileLocations[i] + '/';
}
var newFileStream = isolatedStorage.CreateFile(currentPath + fileName);
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length];
unzip.GetFileStream(currentFileAndDirectory).Read(fileBytes, 0, fileBytes.Length);
unzip.GetFileStream(currentFileAndDirectory).Close();
try
{
newFileStream.Write(fileBytes, 0, fileBytes.Length);
}
catch (Exception ex)
{
Debug.WriteLine("FILE WRITE EXCEPTION: " + ex);
newFileStream.Close();
newFileStream = null;
zipFile.Close();
unzip.Dispose();
}
newFileStream.Close();
newFileStream = null;
}
zipFile.Close();
unzip.Dispose();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
isolatedStorage.DeleteFile(zipFilePath);
}
}
This error appears here:
var newFileStream = isolatedStorage.CreateFile(currentPath + fileName);
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length]; unzip.GetFileStream(currentFileAndDirectory).Read(fileBytes, 0, fileBytes.Length);
unzip.GetFileStream(currentFileAndDirectory).Close();
I debugged it and it fails on
byte[] fileBytes = new byte[unzip.GetFileStream(currentFileAndDirectory).Length];
I checked GetFileStream method
public Stream GetFileStream(string filename)
{
if (fileEntries == null)
fileEntries = ParseCentralDirectory(); //We need to do this in case the zip is in a format Silverligth doesn't like
long position = this.stream.Position;
this.stream.Seek(0, SeekOrigin.Begin);
Uri fileUri = new Uri(filename, UriKind.Relative);
StreamResourceInfo info = new StreamResourceInfo(this.stream, null);
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);
this.stream.Position = position;
if (stream != null)
return stream.Stream;
return null;
}
It throws OutOfMemory exception on this row:
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);

When calculating to report backgroundworker progressBar i'm getting exception cant divide by zero what is wrong?

This is the method:
Getting the Length of the files give 0 already.
public void DownloadFtpContent(object sender ,string file, string filesdirectories,string fn)
{
try
{
BackgroundWorker bw = sender as BackgroundWorker;
string filenameonly = Path.GetFileName(file);
string ftpdirectories = Path.Combine(ftpcontentdir, filesdirectories);
string fileurl = "ftp://" + file;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(fileurl);
reqFTP.Credentials = new NetworkCredential(UserName, Password);
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.Proxy = null;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
if (!Directory.Exists(ftpdirectories))
{
Directory.CreateDirectory(ftpdirectories);
}
FileStream writeStream = new FileStream(ftpdirectories + "\\" + filenameonly, FileMode.Create);
string fnn = ftpdirectories + "\\" + filenameonly;
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
long FileSize = new FileInfo(fnn).Length;
string FileSizeDescription = GetFileSize(FileSize);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(bytesRead), FileSizeDescription);
bw.ReportProgress((int)(((decimal)bytesRead / (decimal)FileSize) * 100), SummaryText);
}
writeStream.Close();
response.Close();
}
catch (WebException wEx)
{
//MessageBox.Show(wEx.Message, "Download Error");
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Download Error");
}
}
}
Already on this line the result is 0:
long FileSize = new FileInfo(fnn).Length;
In fnn i have: c:\myftpdownloads\root\Images\CB 967x330.jpg
Why the result of the Length is 0 ?
And the file is not 0kb size.
EDIT
This is how i'm calling the download method from backgroundworker dowork event:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < numberOfFiles.Count; i++)
{
int fn = numberOfFiles[i].IndexOf(txtHost.Text, 0);
string fn1 = numberOfFiles[i].Substring(txtHost.Text.Length + 1, numberOfFiles[i].Length - (txtHost.Text.Length + 1));
string dirs = Path.GetDirectoryName(fn1);
string filename = Path.GetFileName(fn1);
ftpProgress1.DownloadFtpContent(sender,numberOfFiles[i], dirs, filename);
}
}
In fnn i have: c:\myftpdownloads\root\Images\CB 967x330.jpg Why the result of the Length is 0 ?
It doesn't really matter why the result of the length is 0. It does matter that you divide that number by 0 without any protection.
Just check before you divide:
if( FileSize != 0 ){...}

Split large datafile into multiple file with complete rows

I want to split large data file (5 GB) into multiple files (5 files of 1 GB).
I am using this code:-
string destFileLocation = #"C:\Users\";
int index = 0;
long maxFileSize = 1073741824;
byte[] buffer = new byte[65536];
//int a = buffer.Length;
using (Stream source = File.OpenRead(sourceFileName))
{
try
{
while (source.Position < source.Length)
{
index++;
// Create a new sub File, and read into t
string newFileName = Path.Combine(destFileLocation, Path.GetFileNameWithoutExtension(sourceFileName));
//destinationFile = new StreamWriter(
// string.Format(destinationFileName, fileCounter + 1));
newFileName += "_" + index.ToString() + Path.GetExtension(sourceFileName);
using (Stream destination = File.OpenWrite(newFileName))
{
try
{
while (destination.Position < maxFileSize)
{
int bytes = source.Read(buffer, 0, (int)Math.Min(maxFileSize, buffer.Length));
destination.Write(buffer, 0, bytes);
if (bytes < Math.Min(maxFileSize, buffer.Length))
{
break;
}
}
}
finally
{
destination.Dispose();
destination.Close();
}
}
}
}
finally
{
source.Dispose();
source.Close();
}
}
Now files are splitting between the rows but we need full rows.
Please provide some suggestion.

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