Post an outlook attachment stream to a rest api - c#

I am developping an outlook add-in, i have to upload mailitem attachment using rest api. First i save the attachment to a temp directory and i create a streamreader to that file, how can i post this stream because if i donĀ“t post the stream it creates me empty files with just the specified name:
for (int i = 1; i <= this.Attachments.Count; i++)
{
var fileName = this.Attachments[i].FileName;
Attachments[i].SaveAsFile(Path.GetTempPath() + fileName);
StreamReader stream = new StreamReader(Path.GetTempPath() + fileName);
}
what i must do to achieve it, i need some help. Cheers

Related

Sending DeflateStream file contents to Azure Message Queue

This is about sending/receiving contents of an XML file to/from Azure Service Message Queue using TopicClient in C#.
I am sending contents of a XML file as string, I can see the message on the Azure Queue and can even read its contents properly, so everything works fine when I send a plain text XML file.
But, due to data restrictions on the incoming message on the queue, I had to compress the file before sending it, I am using the C#'s DeflateStream to compress the contents of the file and writing it back to a file. On the receiving end, I am able to read the contents of the file but its not the same as what was sent.
I suspect this is has got something to do with the encoding. Could you please guide me on what I am missing? Thanks in advance.
Sender
public string Compress(FileInfo XMLFile) {
using(FileStream originalFileStream = file.OpenRead()) {
if ((File.GetAttributes(file.FullName) & FileAttributes.Hidden) !=
FileAttributes.Hidden & file.Extension != ".cmp") {
using(FileStream compressedFileStream = File.Create(file.FullName + ".cmp")) {
using(DeflateStream compressionStream = new DeflateStream(compressedFileStream, CompressionMode.Compress)) {
originalFileStream.CopyTo(compressionStream);
}
}
FileInfo info = new FileInfo(directoryPath + "\\" + file.Name + ".cmp");
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", file.Name, file.Length, info.Length);
}
}
return info.FullName;
}
// snippet from the send method
FileInfo XMLfile = new FileInfo(XMLFilePath);
string CompressedXMLFilePath = Compress(XMLfile);
TopicClient myTopicClient = TopicClient.CreateFromConnectionString(AzureConnectionString);
string toSend = File.ReadAllText(CompressedXMLFilePath); // read contents of file compressed with DeflateStream.
myTopicClient.Send(new BrokeredMessage(toSend));
Receiver
var subClient = SubscriptionClient.CreateFromConnectionString(_serviceBusConn, _serviceBustopic, "<subscription name>");
subClient.OnMessage(m =>
{
Console.WriteLine(m.GetBody<string>());
});

Unable to scan Outlook Attachment for encryption

I am trying to detect an encrypted attachment using ICSharpCode.SharpZipLib,
but the code breaks while debugging on this line:
FileStream fileStreamIn = new FileStream(attachtype, FileMode.Open, FileAccess.Read);
Is there any other way through which I can get Outlook attachment and scan for encryption?
if (attachments.Count != 0)
{
for (int i = 1; i <= mail.Attachments.Count; i++)
{
String attachtype = mail.Attachments[i].FileName.ToLower();
if (extensionsArray.Any(attachtype.Contains))
{
FileStream fileStreamIn = new FileStream(attachtype, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
ZipEntry entry = zipInStream.GetNextEntry();
MessageBox.Show("IsCrypted: " + entry.IsCrypted);
}
}
}
I'm assuming you are using Microsoft.Office.Interop.Outlook namespaces.
According to the MSDN the Filename property does the following (source):
Returns a String (string in C#) representing the file name of the
attachment. Read-only.
So the value is only the name of the file, not the location (it does not exist on disk as a accessible file). When supplying just the filaneme into a FileStream it will attempt to open a file with that name in the local directory (which probably does not exist).
It seems from the documentation you'll need to store it using the SaveAsFile method (source) into a temporary file and load a FileStream from that.
So something like:
// Location to store file so we can access the data.
var tempFile = Path.GetTempFileName();
try {
// Save attachment into our file
mail.Attachments[i].SaveToFile(tempFile);
using(var stream = File.OpenRead(tempFile)) {
// Do stuff
}
} finally {
// Cleanup the temp file
File.Delete(tempFile);
}

Fetching attachment from given .eml file and using that attachment to other mail

I am working on code in C#,but not going through on thing that is I have saved some .eml file on my disk now I am parsing each eml file and creating a new mail adding the eml file data to the new mail but I am unable to attach the attachments present in the .eml file to the new mail , can anybody please help?
I am using the follwing code but it shows the error ex = {"The process cannot access the file because it is being used by another process.\r\n":null}
foreach (CDO.IBodyPart attach in msg.Attachments)
{
i++;
string filenm = "C:\\mail_automation\\attachments\\xyz" + i +".eml";
if (File.Exists(filenm))
{
string fn = attach.FileName;
attach.SaveToFile("C:\\mail_automation\\attachments\\xyz" + i + ".eml");
Attachment data = new Attachment(filenm);
mailMessage.Attachments.Add(data);
}
else
{
File.Create(filenm);
string fn = attach.FileName;
attach.SaveToFile("C:\\mail_automation\\attachments\\xyz" + i + ".eml");
Attachment data = new Attachment(filenm);
mailMessage.Attachments.Add(data);
}
You have to extract the attachments and save them to disk first, then fetch it again into the new mail.
Code example here
MailMessage message = new MailMessage();
MemoryStream ms = new MemoryStream(); //store the mail into this ms 'memory stream'
ms.Position = 0;
message.Attachments.Add(new Attachment(ms, attachmentName));

Saving File on Desktop by c#

I am using a web service that returns me some data. I am writing that data in a text file. my problem is that I am having a file already specified in the c# code, where I want to open a dialog box which ask user to save file in his desired location. Here I am posting code which I have used. Please help me in modifying my code. Actually after searching from internet, all are having different views and there is lot of changes in code required where as I do not want to change my code in extent. I am able to write the content in test file but how can I ask user to enter his desire location on computer?
StreamWriter file = new StreamWriter("D:\\test.txt");
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
// Get the response from the Internet resource.
HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
// Read the body of the response from the server.
StreamReader strm =
new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
string content = "";
for (int i = 0; i < symbols.Length; i++)
{
// Loop through each line from the stream,
// building the return XML Document string
if (symbols[i].Trim() == "")
continue;
content = strm.ReadLine().Replace("\"", "");
string[] contents = content.ToString().Split(',');
foreach (string dataToWrite in contents)
{
file.WriteLine(dataToWrite);
}
}
file.Close();
Try this
using (WebClient Client = new WebClient ())
{
Client.DownloadFile("http://www.abc.com/file/song/a.mpeg", "a.mpeg");
}

How to open up a zip file from MemoryStream

I am using DotNetZip.
What I need to do is to open up a zip files with files from the server.
The user can then grab the files and store it locally on their machine.
What I did before was the following:
string path = "Q:\\ZipFiles\\zip" + npnum + ".zip";
zip.Save(path);
Process.Start(path);
Note that Q: is a drive on the server. With Process.Start, it simply open up the zip file so that the user can access all the files. I like to do the same but not store the file on disk but show it from memory.
Now, instead of storing the zip file on the server, I like to open it up with MemoryStream
I have the following but does not seem to work
var ms = new MemoryStream();
zip.Save(ms);
but not sure how to proceed further in terms of opening up the zip file from a memory stream so that the user can access all the files
Here is a live piece of code (copied verbatim) which I wrote to download a series of blog posts as a zipped csv file. It's live and it works.
public ActionResult L2CSV()
{
var posts = _dataItemService.SelectStuff();
string csv = CSV.IEnumerableToCSV(posts);
// These first two lines simply get our required data as a long csv string
var fileData = Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "LogPosts.zip",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, "application/octet-stream");
}
You can use:
zip.Save(ms);
// Set read point to beginning of stream
ms.Position = 0;
ZipFile newZip = ZipFile.Read(ms);
See the documentation for Create a zip using content obtained from a stream.
using (ZipFile zip = new ZipFile())
{
ZipEntry e= zip.AddEntry("Content-From-Stream.bin", "basedirectory", StreamToRead);
e.Comment = "The content for entry in the zip file was obtained from a stream";
zip.AddFile("Readme.txt");
zip.Save(zipFileToCreate);
}
After saving it, you can then open it up as normal.

Categories

Resources