0

I am trying to get the content of attachment. It may be an excel file, Document file or text file whatever it is but I want to store it in database so here I am using this code: -

  foreach (FileAttachment file in em.Attachments)// Here em is type of EmailMessage class
      {
      Console.Write("Hello friends" + file.Name);
      file.Load();
      var stream = new System.IO.MemoryStream(file.Content);
      var reader = new System.IO.StreamReader(stream, UTF8Encoding.UTF8);
      var text = reader.ReadToEnd();
      reader.Close();
      Console.Write("Text Document" + text);
      }

So By printing file.name is showing attachment file name but while printing 'text' on the console it is working if the attachment is .txt type but if it is .doc or .xls type then it is showing some symbolic result. I am not getting any text result. Am I doing something wrong or missing something. I want text result of any kind of file attachment . Please help me , I am beginner in C#

Praveen
  • 55,303
  • 33
  • 133
  • 164
Shyam Dixit
  • 2,325
  • 3
  • 19
  • 27

3 Answers3

2

What you are seeing is what is actually in the file. Try opening one with Notepad.

There is no built-in way in .NET to show the "text contents" of arbitrary file formats. You'll have to create (preferably using third-party libraries that already solve this problem) some kind of logic that extracts plaintext from rich text documents.

See for example How to extract text from Pdf, Word and Excel documents?, Extract text from pdf and word files, and so on.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
2

First, what do you expect when reading a binary file?

Your result is exactly what is expected. A text file can be shown as a string, but a doc or xls file is a binary file. You will see the binary content of the file. You will need to use a tool/lib to get the text/content from a binary file in human readable format.

Peter
  • 27,590
  • 8
  • 64
  • 84
0

TXT type is simple,DOC or XLS are much more complex.You can see TXT because is just text,DOC or XLS or PPT or something else needs to be interpreted by other mechanism. See,for example,you have different colors or font sizes on a Word document,or a chart in an Excel document,how can you show that in a simple TextBox or RichTextBox?Short answer,you can't.

Jota WA
  • 64
  • 3