views:

37

answers:

1

I am reading in a file and want to add MIME header infromation to the top of the file.

For example: I have a text file called test.txt. I read the file into a byte array then want to append the following to the beggining:

Content-Type: text/plain;
     name="test.txt"
Content-Transfer-Encoding: binary
Content-Disposition: attachment;
     filename="test.txt"

How can i get the what the content type is? And how would you reccomend adding this to the beggining of the file? I was planning on creating a string with that information then converting it to a byte array and sticking it on the front of my file buffer but I am worried about running into encoding problems.

+2  A: 

You can't add header information into the file itself; it is transmitted along with the file when you are using certain protocols (chiefly SMTP and HTTP).

EDIT: If you wish to work out the content-type (also known as Internet media type) from the file content, you may wish to look at something like mime-util or Apache Tika.

EDIT 2: The answers to this question will help with content-type detection in .NET:

EDIT 3: If you know the file format you are working on, you can add any arbitary information you wish to it. You will need to special case each file format though. I can't imagine why you want protocol information inside your file, but that's up to you!

EDIT 4: To add text to the beginning of a text file:

static void WriteBeginning(string filename, string insertedtext)
{
    string tempfile = Path.GetTempFileName();
    StreamWriter writer = new StreamWriter(tempfile);
    StreamReader reader = new StreamReader(filename);
    writer.WriteLine(insertedtext);
    while (!reader.EndOfStream)
        writer.WriteLine(reader.ReadLine());
    writer.Close();
    reader.Close();
    File.Copy(tempfile, filename, true);
}

(credit)

Colin Pickard
But I /want/ to add header information to the file itself.
Petey B