Convert Byte [] to PDF - c#

With help of this question C# 4.0: Convert pdf to byte[] and vice versa i was able to convert byte[] to PDF. Byte array length is 25990 approx. When i try to open the PDF it says file is corrupted. What could be the reason?
I tried the BinaryWriter but it creates PDF of 0 KB.
It's a response from a Web Service
Sample Code
WebResponse resp = request.GetResponse();
var buffer = new byte[4096];
Stream responseStream = resp.GetResponseStream();
{
int count;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, responseStream.Read(buffer, 0, buffer.Length));
} while (count != 0);
}
resp.Close();
byte[] memoryBuffer = memoryStream.ToArray();
System.IO.File.WriteAllBytes(#"E:\sample1.pdf", memoryBuffer);
int s = memoryBuffer.Length;
BinaryWriter binaryWriter = new BinaryWriter(File.Open(#"E:\sample2.pdf", FileMode.Create));
binaryWriter.Write(memoryBuffer);

You are reading twice from the stream but only writing one buffer. Change this:
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, responseStream.Read(buffer, 0, buffer.Length));
To this:
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);

It seems your missing some bytes there because you have one unnecessary read. Try this:
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);
} while (count != 0);

Related

Download FTP archive [duplicate]

This question already has answers here:
FtpWebRequest FTP download with ProgressBar
(3 answers)
Closed 2 years ago.
I'm with something new, I'm blocked and I don't know how to do the truth.
I am making a program that downloads by FTP to do a series of steps, the first thing is to download.
Here I have the code that makes the download which works perfect:
public static void DescargarFichero(string ficFTP, string user, string pass, string dirLocal, Boolean UsePassive, Boolean UseBinary)
{
FtpWebRequest dirFtp = ((FtpWebRequest)FtpWebRequest.Create(ficFTP));
dirFtp.KeepAlive = true;
dirFtp.UsePassive = UsePassive;
dirFtp.UseBinary = UseBinary;
// Los datos del usuario (credenciales)
NetworkCredential cr = new NetworkCredential(user, pass);
dirFtp.Credentials = cr;
FtpWebResponse response = (FtpWebResponse)dirFtp.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
using (FileStream writer = new FileStream(dirLocal, FileMode.Create))
{
long length = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[2048];
readCount = responseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writer.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
Console.WriteLine("Descargando...");
}
}
reader.Close();
response.Close();
}
I am doing tests in a console application, but the future is to use windows form and that it looks good, my blocking is this: How can I show this to happen:
while (readCount > 0)
{
writer.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
Console.WriteLine("Descargando...");
}
I can find out that this function is executing and that it is "downloading" I am looking for that every time that cycle is iterating I can return a value without having to break the cycle. My idea is to be able to say If Value is = X then "downloading"
Newbie question? Yes, I am blocked and I don't know how to get out of the "rat race". I hope you can help me.
Showing progress percentage
readCount = responseStream.Read(buffer, 0, bufferSize);
int current = 0; //Create a new int variable to count iterations
while (readCount > 0)
{
writer.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
current++; //Increment the counter
double percentProgress = (current/readCount) * 100; //Calculate the percent
string percentString = percentProgress.ToString() + "%"; //Append a %
Console.WriteLine(percentString); //Write to console
}
See this post if you wish to keep it on one line: Can Console.Clear be used to only clear a line instead of whole console?

CScore MediaFoundationEncoder MP3 Encoder Output Stream Empty

I'm trying to capture an audio stream in CScore and save it in various encodings and to various locations. One of my intended output encodings is MP3 via the MediaFoundationEncoder APIs.
I am able to successfully encode to MP3 when saving to a local file path. However, if I try to write to a memory stream the memory stream completes writing with a 0 length.
What is wrong with this implementation?
Working Local Storage
var fileName = "c:\audio.mp3";
using (var encoder = MediaFoundationEncoder.CreateMP3Encoder(waveFormat, fileName, waveFormat.BytesPerSecond))
{
byte[] buffer = new byte[waveFormat.BytesPerSecond];
int read;
while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
encoder.Write(buffer, 0, read);
}
}
Non-working Memory Stream
using (var outputStream = new MemoryStream())
{
var encoder = MediaFoundationEncoder.CreateMP3Encoder(waveFormat, outputStream, waveFormat.BytesPerSecond);
var buffer = new byte[waveFormat.BytesPerSecond];
int read;
while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
encoder.Write(buffer, 0, read);
}
log.Debug("MP3 File Size: " + outputStream.Length); // <-- Returns as 0
}
You have to dispose the encoder after write, this completes the output stream.
public static byte[] EncodeBytes(byte[] bytes, WaveFormat waveFormat)
{
var outputStream = new MemoryStream();
var encoder = MediaFoundationEncoder.CreateMP3Encoder(waveFormat, outputStream, waveFormat.BytesPerSecond);
var buffer = new byte[waveFormat.BytesPerSecond];
var inputStream = new MemoryStream(bytes);
int read;
while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
encoder.Write(buffer, 0, read);
}
encoder.Dispose();
return outputStream.ToArray();
}

HTTP Response Stream to file in c#

I want to write my http response to a file but my file is always empty. Why?
using (Stream outputfile = File.OpenWrite(objecttype + ".txt"))
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = context.Response.OutputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputfile.Write(buffer, 0, bytesRead);
}
outputfile.Flush();
outputfile.Close();
}

How to receive large file over networkstream c#?

Im connecting 2 devices over TCPClient and TCPListener and im sending just a string for now and its all working:
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();
and then
bytesRead = clientStream.Read(message, 0, 4096);
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("Mensageee"+ encoder.GetString(message, 0, bytesRead));
But now i need to send a large file over it like 10mb or maybe more so should i use this?
string doc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
byte[] file = File.ReadAllBytes(doc + filedir)
byte[] fileBuffer = new byte[file.Length];
TcpClient clientSocket = new TcpClient(ip, port);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(file.ToArray(), 0, fileBuffer.GetLength(0));
networkStream.Close();
And how should i receive all this file and then save it somewhere?
Any help is welcome thanks o/
The short answer is, you send a byte[] multiple times...
Essentially, you will need to fill a buffer ('byte[]') with a subset of the file:
int count = fileIO.Read(buffer, 0, buffer.Length);
And then send the buffer over the socket:
clientSocket.Send(buffer, 0, count);
Just do these two processes until you have sent the entire file... (Which will be when count <= 0) However, the server has to know how many bytes to read... so we should start out by sending a Int64 with the file's length.
What we have so far...
using (var fileIO = File.OpenRead(#"C:\temp\fake.bin"))
using(var clientSocket = new System.Net.Sockets.TcpClient(ip, port).GetStream())
{
// Send Length (Int64)
clientSocket.Write(BitConverter.GetBytes(fileIO.Length, 0, 8));
var buffer = new byte[1024 * 8];
int count;
while ((count = fileIO.Read(buffer, 0, buffer.Length)) > 0)
clientSocket.Write(buffer, 0, count);
}
Server Side
Int64 bytesReceived = 0;
int count;
var buffer = new byte[1024*8];
// Read length - Int64
clientStream.Read(buffer, 0, 8);
Int64 numberOfBytes = BitConverter.ToInt64(buffer, 0);
using(var fileIO = File.Create("#c:\some\path"))
while(bytesReceived < numberOfBytes && (count = clientStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileIO.Write(buffer, 0, count);
bytesReceived += count;
}

How to calculate downloading time in c#(FTP)

I want to calculate downloading time in my ftp download manager.
I am using these code to download file through ftp.
try
{
string DirectoryCreate = localPath;
if (!Directory.Exists(DirectoryCreate))
{
Directory.CreateDirectory(DirectoryCreate);
}
FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://xxxxxx.com);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
Stream responseStream = responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(localPath + "\\" + fileName, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
responseStream.Close();
writeStream.Close();
requestFileDownload = null;
responseFileDownload = null;
}
catch(WebException ex)
{
}
Can anyone please say me what i should change in my code for calculating download time.
There would be great appreciation if someone could help me.
DateTime t1 = DateTime.Now;
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
DateTime t2 = DateTime.Now;
TimeSpan diff = t2 - t1;//you can return diff or display it using its properties ..
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
responseStream.Close();
writeStream.Close();
requestFileDownload = null;
responseFileDownload = null;
}
catch(WebException ex)
{
}
stopwatch.Stop();
stopwatch.Elapsed // this will give you the elapsed time

Categories

Resources