CRM File attachments - c#

CRM saves attachements in AnnotationBase base table.
How can I convert the text in the DocumentBody entity back to file and save it the file system.
I’m comfortable with plugins and workflow activities. But can't figure how to convert a string in the database to a file on the system.

using(FileStream fs = new FileStream("fileName", FileMode.Create,
FileAccess.Write))
{
StreamWriter writer = new StreamWriter(fs);
writer.Write(yourString);
fs.Flush();
}
[EDIT]
If we're talking about BASE64 strings then try this:
using (FileStream fs = new FileStream("fileName", FileMode.Create,
FileAccess.Write))
{
byte[] bytes = Convert.FromBase64String(yourString);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
}

Grrr.
Look all day, then find the answer 5mins after posting the question.
File.WriteAllBytes("c:\\word1.docx", System.Convert.FromBase64String(str));

Related

How to save attachments?

I am using MailKit/MimeKit 1.2.7 (latest NuGet version).
I have been reading the API documentation and several posts on stackoverflow. But I still wasn't able to successfully save email attachments as a file.
Here is my current code:
var mimePart = (attachment as MimePart);
var memoryStream = new MemoryStream();
mimePart.ContentObject.DecodeTo(attachmentStream);
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
memoryStream.CopyTo(fileStream);
}
I have been trying this code with different kinds of attachments. The created file on my disc is always empty.
What am I missing?
The problem with the above code is that you are forgetting to reset the memoryStream.Position back to 0 :-)
However, a better way of doing what you want to do is this:
var mimePart = (attachment as MimePart);
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
mimePart.ContentObject.DecodeTo(fileStream);
}
In other words, there's no need to use a temporary memory stream.

Filestream.write does not work

I used the following code to write on *.txt file, but nothing happens. Even, there is no exception.
FileStream fs = new FileStream(#"D:\file.txt",FileMode.OpenOrCreate,FileAccess.Write,FileShare.None); //Creating a stream with certain features to a file
StreamWriter writer = new StreamWriter(fs); //Use the fs to write
// writer.WriteLine(Text.Text); none of the following methods works
writer.Write("aaaaaaaaaaaa");
fs.Close();
Thanks
Try to enclose it in a using block like this:
using ( FileStream fs = new FileStream(#"D:\file.txt",FileMode.OpenOrCreate,FileAccess.Write,FileShare.None))
using (StreamWriter fw = new StreamWriter(fs))
{
fw.Write("aaaaaaaaaaaa");
}
A StreamWriter buffers data before writing it to the underlying stream. You need to flushes the buffer by disposing the StreamWriter

Is there a way to create a text file using a string name in C#

I'm not sure if it's possible. I usually create txt files like this:
FileStream fs = new FileStream("c:\\textFile.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
but instead of using "c:\textFile.txt" I want to create a file using a string name. Is there a way to do it?
Of course. The first argument to the FileStream constructor takes a string. You've just passed it a string literal (defined in your source code file). It sounds like you want to pass a string variable instead:
string path = // get string from somewhere. A file save dialog, maybe?
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
May I suggest that you spend some time with a C# tutorial? Microsoft has some good tutorials and samples. With all due respect, and we were all there once, you've got some holes in your knowledge that will trip you up.
I'm not sure I'm following what you're asking for. You just asked if u could do that:
string filename = "c:\\textFile.txt";
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
or as you specified
FileStream fs = new FileStream(YourTextBox.Text, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);

Creating a UTF8 text file instead of ANSI

I have this snippet of code to write a file asynchronously:
private static async Task WriteTextAsync(string filePath, string text)
{ //Writes to our output files
byte[] encodedText = Encoding.UTF8.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}
The created text file is still ANSI format despite having set the Encoding.UTF8. There's 15 overloaded constructors for the FileStream class, and it's not obvious at all to me where I should set this if not on the encoded text.
I can tell the file is ANSI, because when I open it in TextPad and view the file statistics it lists ANSI as the Code Set:
Having problems, because MySQL LOAD INFILE is not reading the file properly, after reading the answers I believe it has something to do with the BOM, but not sure.
I tried this (for BOM):
byte[] encodedText = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(Encoding.UTF8.GetBytes(text)).ToArray();
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
Textpad then saw it as UTF8, MySQL LOAD INFILE still failed. Resaved in Textpad, and MySQL saw it properly.
Changed code to this:
using (TextWriter writer = File.CreateText(filePath))
{
await writer.WriteAsync(text);
}
This seemed to work in both. I'm not sure what the issue is with MySQL LOAD INFILE regarding this.
No, it is definitely UTF-8:
byte[] encodedText = Encoding.UTF8.GetBytes(text);
That can only give you UTF-8; you then write encodedText to the stream.
However! UTF-8 will look identical to ASCII/ANSI for any characters in the 0-127 range. It only looks different above that. False positive?
I believe you forget to write BOM header to the beginning of the file. As you are using FileStream (and not some sort of TextWriter) you have to write it manually.
In case of UTF-8 it should be "EF BB BF"

GZipStream works but extension is lost

I am using following code to zip a file and it works fine but when I decompress with WinRar I get the original file name without the extension, any clue why if filename is myReport.xls when I decompress I get only myReport ?
using (var fs = new FileStream(fileName, FileMode.Open))
{
byte[] input = new byte[fs.Length];
fs.Read(input, 0, input.Length);
fs.Close();
using (var fsOutput = new FileStream(zipName, FileMode.Create, FileAccess.Write))
using(var zip = new GZipStream(fsOutput, CompressionMode.Compress))
{
zip.Write(input, 0, input.Length);
zip.Close();
fsOutput.Close();
}
}
GZip compresses only one file - without knowing the name. Therefore if you compress the file myReport.xls you should name it myReport.xls.gz. On decompression the last file extension will be removed so you end up with the original filename.
That its the way how it is used in Unix/Linux for ages...
Very weird indeed. A brief search came up with the following:
http://dotnetzip.codeplex.com/discussions/268293
Which says that GZipStream has no way of knowing the name of the stream that is being written, and suggests you set the FileName property directly.
Hope that helps.

Categories

Resources