Read docx file from VM and write it down to a stream - c#

I have a .docx file located on my virtual machine desktop which I want to write down to a stream.
So far this is what I have tried
byte[] buffer = new byte[32768];
string path = #"\\officeblrhome.somedomain\UserData$\username\Desktop\filename.docx";
var memoryStr = new MemoryStream();
memoryStr.Write(System.IO.File.ReadAllBytytes(path), 0 , buffer.Length);
using (WordprocessingDocumenet doc = WordprocessingDocument.Open(memoryStr, true)
And I get the an error that the file contains corrupted data. Is it possible that my path is wrong? If it is how to get the valid path from the VM? The word file itself is not corrupted.

I made few changes to the code and seems that it's working
byte[] buffer = System.IO.File.ReadAllBytytes(path);
stream.Flush();
stream.Position = 0;

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());
}
}

C# read IFormFile into byte[]

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());
}
}

finding file in root of wpf application

I'm trying to load a file with pack://application: The file is situated in the root of my project but I keep getting a null reference error. However When I do an absolute reference it finds the file and loads just fine.
What am I missing here?
This doesn't work
var txt = Application.GetContentStream(new Uri(#"pack://application:,,,/Layout.xml"));
string full = new StreamReader(txt.Stream).ReadToEnd();
or any variation with Pack://Application,,,/
This works, but I don't want to use it and seems bad practice anyway
var path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, (AppDomain.CurrentDomain.BaseDirectory.Length - 10));
var txt = path + #"Layout.xml";
string full = new StreamReader(txt).ReadToEnd();
First, ensure that the file is definitely copied into your output ./bin/ directory on compile:
This worked perfectly for me in my WPF application:
const string imagePath = #"pack://application:,,,/Test.txt";
StreamResourceInfo imageInfo = Application.GetResourceStream(new Uri(imagePath));
byte[] imageBytes = ReadFully(imageInfo.Stream);
If you want to read it as binary (e.g. read an image file), you'll need this helper function. You probably won't need this, as you're reading an .xml file.
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
For more, see Microsoft on Pack URIs in WPF.
I'm not familiar with the way you are trying to achieve this. I use to solve this kind of problem differently:
First, embed the file you are trying to access in you application. This is done by setting the Build-Step-Property of the File (Properties-Window, when file is selected in VS) to Embedded Resource.
In your application, you can recieve a stream to that resource like that:
var stream = this.GetType().Assembly.GetManifestResourceStream("Namespace.yourfile.txt");
If you are unsure of the string you have to pass to GetManifestResourceStream(..), you can inspect what embedded resources are available and look for the one that is accociated with your file like so:
var embeddedResources = this.GetType().Assembly.GetManifestResourceNames()

How to pack a dll file

I'm trying to "pack" a dll file into a file that contains other resources. I'm reading the bytes of the DLL and writnig them back in the "package" file, but when I unpack everything, the DLL is corruped.
I can see that I'm writing the "package" file incorrectly ( input is 8kb - output is 9kb and dll is not working ) and I can't seem to get why this is happening.
I read the bytes from the input file, put them into memorystream via binarywriter and then write them to the "package" file using File.WriteAllBytes.
byte[] bytes = File.ReadAllBytes(fileDest[i]);
using (MemoryStream ms = new MemoryStream())
{
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(count); //int32
bw.Write(version); //int32
for (int i = 0; i < count; i++)
{
bw.Write(lengthofbytes);
bw.Write(someinfo); // string
bw.Write(filecontents); // bytes
}
byte[] bytes = ms.ToArray();
File.WriteAllBytes("some.dll", bytes);
}
What I'm trying to do is combine a bunch of files in one file and then "unpack" them where they need to be. Unfortunately one of the files has to be a .DLL

sharpziplib compressed files to be uncompressed externally

I have a scenario where by I want to zip an email attachment using SharpZipLib. Then the end user will open the attachment and will unzip the attached file.
Will the file originally zipped file using SharpZipLib be easily unzipped by other programs for my end user?
It depends on how you use SharpZipLib. There is more than one way to compress the data with this library.
Here is example of method that will create a zip file that you will be able to open in pretty much any zip aware application:
private static byte[] CreateZip(byte[] fileBytes, string fileName)
{
using (var memoryStream = new MemoryStream())
using (var zipStream = new ZipOutputStream(memoryStream))
{
var crc = new Crc32();
crc.Reset();
crc.Update(fileBytes);
var zipEntry =
new ZipEntry(fileName)
{
Crc = crc.Value,
DateTime = DateTime.Now,
Size = fileBytes.Length
};
zipStream.PutNextEntry(zipEntry);
zipStream.Write(fileBytes, 0, fileBytes.Length);
zipStream.Finish();
zipStream.Close();
return memoryStream.ToArray();
}
}
Usage:
var fileBytes = File.ReadAllBytes(#"C:/1.xml");
var zipBytes = CreateZip(fileBytes, "MyFile.xml");
File.WriteAllBytes(#"C:/2.zip", zipBytes);
This CreateZip method is optimized for the cases when you already have bytes in memory and you just want to compress them and send without even saving to disk.

Categories

Resources