Convert mp4 file to byte array and string - c#

I working on project to upload files into firebase real-time database using firesharp in WinForm c#.
I searched a lot to understand how to do this.
I know about the option to write File.ReadAllBytes(), but I want to run the app on weak PC, with 4 GB ram, and he is very slow.
I succeeded to upload an image, it's work good.
I find something about Stram option, but I don't know how to do it with converting to String.
Sorry about my English.

You can convert the file to binary, and the binary can be saved as arrays and strings.
//Read file to byte array
FileStream stream = File.OpenRead(#"c:\path\to\your\file\here.txt");
byte[] fileBytes= new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
//Begins the process of writing the byte array back to a file
using (Stream file = File.OpenWrite(#"c:\path\to\your\file\here.txt"))
{
file.Write(fileBytes, 0, fileBytes.Length);
}
https://www.codeproject.com/Questions/636646/Csharp-file-to-Byte-Array-and-Byte-Array-to-File
FileStream st = new FileStream(#"C:\2.jpg", FileMode.Open);
byte[] buffer = new byte[st.Length];
st.Read(buffer, 0, (int)st.Length);
st.Close();
Console.ReadLine();
https://social.msdn.microsoft.com/Forums/en-US/648bd8b2-74ec-4054-9c68-68190b600971/how-to-convert-a-file-to-binary?forum=csharplanguage

Related

C# ASP.NET MVC application with file type input on a Mac [duplicate]

I am trying to read an IFormFile received from a HTTP POST request like this:
public async Task<ActionResult> UploadDocument([FromForm]DataWrapper data)
{
IFormFile file = data.File;
string fileName = file.FileName;
long length = file.Length;
if (length < 0)
return BadRequest();
using FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate);
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, (int)file.Length);
...
}
but something is wrong, after this line executes:
fileStream.Read(bytes, 0, (int)file.Length);
all of the elements of bytes are zero.
Also, the file with the same name is created in my Visual Studio project, which I would prefer not to happen.
You can't open an IFormFile the same way you would a file on disk. You'll have to use IFormFile.OpenReadStream() instead. Docs here
public async Task<ActionResult> UploadDocument([FromForm]DataWrapper data)
{
IFormFile file = data.File;
long length = file.Length;
if (length < 0)
return BadRequest();
using var fileStream = file.OpenReadStream();
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, (int)file.Length);
}
The reason that fileStream.Read(bytes, 0, (int)file.Length); appears to be empty is, because it is. The IFormFile.Filename is the name of the file given by the request and doesn't exist on disk.
Your code's intent seems to be to write to a FileStream, not a byte buffer. What it actually does though, is create a new empty file and read from it into an already cleared buffer. The uploaded file is never used.
Writing to a file
If you really want to save the file, you can use CopyTo :
using(var stream = File.Create(Path.Combine(folder_I_Really_Want,file.FileName))
{
file.CopyTo(stream);
}
If you want to read from the uploaded file into a buffer without saving to disk, use a MemoryStream. That's just a Stream API buffer over a byte[] buffer. You don't have to specify the size but that reduces reallocations as the internal buffer grows.
Reading into byte[]
Reading into a byte[] through MemoryStream is essentially the same :
var stream = new MemoryStream(file.Length);
file.CopyTo(stream);
var bytes=stream.ToArray();
The problem is that you are opening a new filestream based on the file name in your model which will be the name of the file that the user selected when uploading. Your code will create a new empty file with that name, which is why you are seeing the file in your file system. Your code is then reading the bytes from that file which is empty.
You need to use IFormFile.OpenReadStream method or one of the CopyTo methods to get the actual data from the stream.
You then write that data to your file on your file system with name you want.
var filename ="[Enter or create name for your file here]";
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate))
//Create the file in your file system with the name you want.
{
using (MemoryStream ms = new MemoryStream())
{
//Copy the uploaded file data to a memory stream
file.CopyTo(ms);
//Now write the data in the memory stream to the new file
fs.Write(ms.ToArray());
}
}

Converting .vox audio files to .wav or .mp3 with NAudio

I am trying to convert .vox to .mp3 or .wav with NAudio with the code below:-
var bytes = GetBytes(new FileInfo(#"D:\path\to\vox-file.vox"));
using (var writer = new WaveFileWriter(#"D:\path\to\wav-file.wav", new WaveFormat(8000, 8, 2)))
{
writer.Write(bytes, 0, bytes.Length);
}
However the converted .wav file I am getting has very distorted audio and its not listenable. Am I missing some configuration with NAudio?
I was able to convert .vox files to .wav with the following:-
var bytes = GetBytes(new FileInfo(#"path-to.vox"));
using (var writer = new WaveFileWriter(#"path-to.wav", Mp3WaveFormat.CreateMuLawFormat(8000, 1)))
{
writer.Write(bytes, 0, bytes.Length);
}
The important bit here is this part: Mp3WaveFormat.CreateMuLawFormat(8000, 1), this is basically some kind of format/configuration for the .wav file which you want to be created and these values may vary depending upon your .vox files

Append WAV Header in NAudio

I am trying to convert audio MP3 files to WAV with a standard rate (48 KHz, 16 bits, 2 channels) by opening with "MediaFoundationReaderRT" and specifying the standard settings in it.
After the file is converted to PCM WAV, when I try to play the WAV file, it gives corrupt output:
Option 1 -
WaveStream activeStream = new MediaFoundationReaderRT([Open "MyFile.mp3"]);
WaveChannel32 waveformInputStream = new WaveChannel32(activeStream);
waveformInputStream.Sample += inputStream_Sample;
I noticed that if I read the audio data into a memory stream (wherein it appends the WAV header via "WaveFileWriter"), then things work fine:
Option 2 -
WaveStream activeStream = new MediaFoundationReaderRT([Open "MyFile.mp3"]);
MemoryStream memStr = new MemoryStream();
byte[] audioData = new byte[activeStream.Length];
int bytesRead = activeStream.Read(audioData, 0, audioData.Length);
memStr.Write(audioData, 0, bytesRead);
WaveFileWriter.CreateWaveFile(memStr, audioData);
RawSourceWaveStream rawSrcWavStr = new RawSourceWaveStream(activeStream,
new WaveFormat(48000, 16, 2));
WaveChannel32 waveformInputStream = new WaveChannel32(rawSrcWavStr);
waveformInputStream.Sample += inputStream_Sample;
However, reading the whole audio into memory is time-consuming. Hence I am looking at "Option 1" as noted above.
I am trying to figure out as to what exactly is the issue. Is it that the WAV header is missing which is causing the problem?
Is there a way in "Option 1" where I can append the WAV header to the "current playing" sample data, instead of converting the whole audio data into memory stream and then appending the header?
I'm not quite sure why you need either of those options. Converting an MP3 file to WAV is quite simple with NAudio:
using(var reader = new MediaFoundationReader("input.mp3"))
{
WaveFileWriter.CreateWaveFile("output.wav", reader);
}
And if you don't need to create a WAV file, then your job is already done - MediaFoundationReader already returns PCM from it's Read method so you can play it directly.

System.byte error while reading a pdf file in C#

i have tried every possible solution that is given on website.
private byte[] GetBinaryFile()
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
return bytes;
}
This is what i was trying to Read from the fileuploader which didn't work. Then i changed the idea i uploaded the file on the server first and then i was trying to read but that again gave me the same error of system.byte(). Thing is it does not return the byte format of the pdf but it worked perfectly on my local system does it has anything to do with the server? Any help will be appreciated
you can try this:-
byte[] bytes = new byte[FileUpload1.PostedFile.ContentLength];
bytes = FileUpload1.FileBytes;

Using Box.V2 API, a DownloadStreamAsync call is resulting in corrupt file

I'm working on a small program to pull a file from a Box.com account. Using the Box C# SDK, I have the following code:
BoxFile file = await Client.FilesManager.GetInformationAsync(item.Id);
byte[] bytes = new byte[file.Size.Value];
using (FileStream fileStream = new FileStream(dlg.FileName, FileMode.Create, System.IO.FileAccess.Write))
using (Stream stream = await Client.FilesManager.DownloadStreamAsync(file.Id))
{
stream.Read(bytes, 0, (int)file.Size.Value);
fileStream.Write(bytes, 0, bytes.Length);
}
However, when I try to pull an image the resulting file is an image with the correct width and height but only a top slice has pixel data. The remainder of the image is black. The file size is correct.
If I pull a docx or pptx file and open them in Word or PowerPoint I get a corrupt file message. The file size is correct.
If the file is a simple txt file, it seems to be successful.
What am I doing wrong?
The stream will make the content available in chunks as data is returned from the server. The single stream.Read call is only fetching the first chunk, which is why the top slice of the image appears correct but the rest of the image is empty.
To resolve this, continue reading from the stream until it indicates that there is no additional content.
using (Stream stream = await Client.FilesManager.DownloadStreamAsync(file.Id))
{
int bytesRead;
var buffer = new byte[8192];
do
{
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
await fileStream.WriteAsync(buffer, 0, bytesRead);
} while (bytesRead > 0);
}

Categories

Resources