C#: downloading and attaching PDFs to MailMessage are corrupt - c#

I am trying to first download a pdf as a string and then attach it to a MailMessage. Here is what I have done so far
string htmlAttachment = webClient.DownloadString((HttpUtility.HtmlDecode(dictIterator.Value)));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(htmlAttachment);
writer.Flush();
stream.Position = 0;
msg.Attachments.Add(new Attachment((Stream)stream, dictIterator.Key));
But whenever I open the pdf attachment, it says, Insufficient data for an image'. Is it something related to encoding and should I directly download it as a stream rather than first getting it asstring`??

Yes, you should download the file in Binary (Not as string.. No encoding involved.. Just pure binary).
PS - Try also saving the file locally to the disk, before attaching it. And then open it from the disk.
It will eliminate the unlikely possibility of MailMessage being the problem.

Related

Issues with saving XML file (C#)

I'm trying to make a config file from an XML file, but I can't figure out how to save the file after I add to it. I can read from the file fine, so I know it's not an issue with where it's located, but I still don't know how to save it.
I've looked around for about 2 hours and can't figure out the problem. I'm know my way around c# but am completely new to XML.
public async Task CreateReaction(string name, DiscordMessage message, DiscordEmoji emoji, DiscordRole role)
{
string path = #"E:\Visual Studio\repos\JustHangoutBot\bin\Debug\netcoreapp1.1\configs\reactions.xml";
XDocument doc = XDocument.Load(path);
await message.CreateReactionAsync(emoji);
XElement root = new XElement(name);
root.Add(new XElement("MessageID", message.Id));
root.Add(new XElement("ReactionID", emoji.Id));
root.Add(new XElement("RoleID", role.Id));
doc.Element("Reactions").Add(root);
byte[] byteArray = Encoding.UTF8.GetBytes(path);
MemoryStream stream = new MemoryStream(byteArray);
doc.Save(stream);
}
I think the problem is somewhere in the last three lines. I've seen tutorials of people saving the file by just using doc.Save("reactions.xml") for example, but I get the error of not being able to convert from string to Stream.
Any help would be appreciated. Thank you in advance!
This will do it:
using (var fileStream = System.IO.File.OpenWrite("path to the file you want to write"))
{
doc.Save(fileStream);
}
When you do this:
byte[] byteArray = Encoding.UTF8.GetBytes(path);
MemoryStream stream = new MemoryStream(byteArray);
doc.Save(stream);
What's happening is
You're opening the file at path and reading it into a byte array.
You're creating a MemoryStream that has those bytes as its content
You're saving that document to the MemoryStream.
Under the hood a MemoryStream is just an array of bytes in memory. So it's writing the file to memory, not to a file.
File.OpenWrite(path) opens a FileStream with the specified path. If the file doesn't exist it creates it. If the file does exist it will overwrite it.
So when you call doc.Save(fileStream) you're writing to the file.

Adobe Reader could not open 'StreamTest5.pdf' because it is either not a supported file or file has been damaged error

I am trying to create a pdf file using file stream and while the file is being created in the specified folder of the path, when I try to open the file Adobe Reader is throwing the error that I mentioned above in the title. I am not sure what I am doing wrong but I would greatly appreciate it if someone could look into it and help me out. Thank you!. Here is my code for the filestream:
System.IO.FileStream wFile;
byte[] byteData = null;
byteData = Encoding.ASCII.GetBytes("FileStream Test");
string filePath = $"{_ApplicationPath}PrintedResults\\StreamTest5.pdf";
wFile = new FileStream(filePath, FileMode.Create);
wFile.Write(byteData, 0, byteData.Length);
wFile.Close();
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
Console.WriteLine("This is a test stream file");
}
System.Diagnostics.Process.Start(filePath);
You are writing a text file with the contents "FileStream Test" but naming it with a file extension of ".PDF". This is not a PDF file. It is a text file with a misleading name. Adobe Reader is correctly reporting that it is not a valid PDF.
This is not an answer but I don't have enough reputation to add it as a comment:
You might want to look to 3rd party library offered by http://www.dynamicpdf.com/
Their free evaluation version is quite capable and it is not time limited as they say on their website. With a little more effort you can create quite complicated PDFs with only the evaluation version!

Chrome not unzipping gzip file if the gzip file was created by combining multiple gzip files

I am creating two gzip files, one which contains only a single gzip member, where as the second one contains 2 gzip members (two files concatenated into a single gzip file).
When I try to download this through a web server, chrome decompresses the first file fine and shows the contents as is.
But when downloading the second file, chrome seems to decompress only the first member and the second member is left uncompressed.
I tried opening the second file using 7zip and verified that the contents are fine.
Below is the code I am using to generate the two files in C#
FileStream fileStream = new FileStream("D:\\single_big_gzip.gz", FileMode.Create);
FileStream fileStream2 = new FileStream("D:\\multiple_gzip_files.gz", FileMode.Create);
// Write to First file
GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress, false);
StreamWriter writer = new StreamWriter(gzipStream);
writer.WriteLine("hello world!");
writer.Flush();
gzipStream.Close();
fileStream.Close();
// write to second file
gzipStream = new GZipStream(fileStream2, CompressionMode.Compress, true);
writer = new StreamWriter(gzipStream);
writer.WriteLine("Hello world!");
writer.Flush();
gzipStream.Close();
gzipStream = new GZipStream(fileStream2, CompressionMode.Compress, true);
writer = new StreamWriter(gzipStream);
writer.WriteLine("Bye Bye Birdie!");
writer.Flush();
gzipStream.Close();
fileStream2.Close();
Any idea how I can get chrome to decompress the entire second file?
Thank you.
Though RFC 1952 specifies that "A gzip file consists of a series of "members" (compressed data sets).", and though gzip properly decodes such streams, browsers generally are not compliant with the standard and will only decode the first member.

Sent Zip file through mail in MVC3

I have use ICSharpCode.SharpZipLib.Zip library for creating Zip file it's working fine, but when i have attach this Zip file to mail attachment, mail is not sent due to attached zip file,
here is code for attaching zip file to mail
System.Net.Mail.Attachment attachment = null;
try
{
MemoryStream memoryStream = new MemoryStream();
attachment = new System.Net.Mail.Attachment(memoryStream, "test.zip");
}
catch (Exception e)
{
return false;
}
please know me how i can send zip file through mail?.
Your code
MemoryStream memoryStream = new MemoryStream();
attachment = new System.Net.Mail.Attachment(memoryStream, "test.zip");
passes a Stream, but that Stream is empty (there's nothing in memoryStream).
If you want to use a MemoryStream, you must read the contents of the ZIP file into memory. You can also use a FileStream if the ZIP is already on disk.
If using a MemoryStream, be sure and set its position 0.
memoryStream.Position = 0;
Depending on how you are using SharpZipLib, you may have access to a ZipOutputStream. If you do, I think you could use that.
There could be lot of reasons for the issue,
Check file date & time
Size of the file ( Based on server settings)
Try different formats (rar,7z, etc)

Unzip file (odt or docx) in a memory stream

I have been developing an web application with Asp.Net and I'm using SharpZipLib to work with odt files (from Open Office) and in the future docx files (for ms office). I need to open an odt file (like a zip file) change a xml file inside it, zip again and give it to the browser send to my client.
I can do this in file system but it will get a space in my disk temporarily and we don't want it. I would like to do this in memory (with a MemoryStream class), but I don't know how to unzip folders/files in a memory stream with SharpZipLib, change and use it to zip again. Is there any sample about how to do this?
Thank you
You can use something like
Stream inputStream = //... File.OpenRead(...);
//for read file
ZipInputStream zipInputStream = new ZipInputStream(inputStream));
//for output
MemoryStream memoryStream = new MemoryStream();
using ( ZipOutputStream zipStream = new ZipOutputStream(memoryStream))
{
ZipEntry entry = new ZipEntry("...");
//...
zipStream.PutNextEntry(entry);
zipStream.Write(data, 0, data.Length);
//...
zipStream.Finish();
zipStream.Close();
}
Edit ::
You need in general unZip your file, get ZipEntry , change , and write in ZipOutputStream with MemoryStream.
Use this article http://www.codeproject.com/KB/cs/Zip_UnZip.aspx

Categories

Resources