4

多くの文字列行とバイトエンコードされたデータの一部を含む混合ファイルがあります。例:

--Begin Attach
Content-Info: /Format=TIF
Content-Description: 30085949.tif (TIF File)
Content-Transfer-Encoding: binary; Length=220096
II*II* Îh  ÿÿÿÿÿÿü³küìpsMg›Êq™Æ™Ôd™‡–h7ÃAøAú áùõ=6?Eã½/ô|û ƒú7z:>„Çÿý&lt;þ¯úýúßj?å¿þÇéöûþ“«ÿ¾ÁøKøÈ%ŠdOÿÞÈ<,Wþ‡ÿ·ƒïüúCÿß%Ï$sŸÿÃÿ÷‡þåiò>GÈù#ä|‘ò:#ä|Š":#¢:;ˆèŽˆèʤV‘ÑÑÑÑÑÑÑÑÑçIþ×o(¿zHDDDDDFp'.Ñ:ˆR:aAràÁ¬LˆÈù!ÿÿï[ÿ¯Äàiƒ"VƒDÇ)Ê6PáÈê$9C”9C†‡CD¡pE@¦œÖ{i~Úý¯kköDœ4ÉU”8`ƒt!l2G
--End Attach--

私はストリームリーダーでファイルを読み込もうとしています:

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Davide\Desktop\20041230000D.xmm")

ファイルを 1 行ずつ読み取り、行が「Content-Transfer-Encoding: binary; Length=220096」と等しい場合、次のすべての行を読み取り、「ファイル名」(この場合は 30085949.tif) ファイルを書き込みます。しかし、バイトデータではなく文字列を読んでおり、結果ファイルが破損しています(今はtiffファイルで試しています)。私への提案はありますか?

解決策 返信ありがとうございます。私はこの解決策を採用しました: BinaryReader を拡張する LineReader を作成しました:

 public class LineReader : BinaryReader
    {
        public LineReader(Stream stream, Encoding encoding)
            : base(stream, encoding)
        {

        }

        public int currentPos;
        private StringBuilder stringBuffer;

        public string ReadLine()
        {
            currentPos = 0;

            char[] buf = new char[1];

            stringBuffer = new StringBuilder();
            bool lineEndFound = false;

            while (base.Read(buf, 0, 1) > 0)
            {
                currentPos++;
                if (buf[0] == Microsoft.VisualBasic.Strings.ChrW(10))
                {
                    lineEndFound = true;
                }
                else
                {                   
                    stringBuffer.Append(buf[0]);                    
                }
                if (lineEndFound)
                {
                    return stringBuffer.ToString();
                }

            }
            return stringBuffer.ToString();

        }

    }

Microsoft.VisualBasic.Strings.ChrW (10)は改行です。ファイルを解析すると:

    using (LineReader b = new LineReader(File.OpenRead(path), Encoding.Default))
    {
        int pos = 0;
        int length = (int)b.BaseStream.Length;
        while (pos < length)
        {
            string line = b.ReadLine();
            pos += (b.currentPos);

            if (!beginNextPart)
            {
                if (line.StartsWith(BEGINATTACH))
                {
                    beginNextPart = true;

                }
            }
            else
            {
                if (line.StartsWith(ENDATTACH))
                {
                    beginNextPart = false;
                }
                else
                {
                    if (line.StartsWith("Content-Transfer-Encoding: binary; Length="))
                    {
                        attachLength = Convert.ToInt32(line.Replace("Content-Transfer-Encoding: binary; Length=", ""));
                        byte[] attachData = b.ReadBytes(attachLength);
                        pos += (attachLength);
                        ByteArrayToFile(@"C:\users\davide\desktop\files.tif", attachData);
                    }
                }
            }
        }
    }

ファイルからバイト長を読み取り、次の n バイトを読み取ります。

4

1 に答える 1

3

ここでの問題は、 StreamReader がファイルを読み取る唯一のものであると想定し、その結果、先読みすることです。最善の策は、ファイルをバイナリとして読み取り、適切なテキスト エンコーディングを使用して、独自のバッファーから文字列データを取得することです。

どうやらファイル全体をメモリに読み込むことを気にしないので、次のように開始できます。

byte[] buf = System.IO.File.ReadAllBytes(@"C:\Users\Davide\Desktop\20041230000D.xmm");

次に、テキスト データに UTF-8 を使用していると仮定します。

int offset = 0;
int binaryLength = 0;
while (binaryLength == 0 && offset < buf.Length) {
    var eolIdx = Array.IndexOf(offset, 13); // In a UTF-8 stream, byte 13 always represents newline
    string line = System.Text.Encoding.UTF8.GetString(buf, offset, eolIdx - offset - 1);

    // Process your line appropriately here, and set binaryLength if you expect binary data to follow

    offset = eolIdx + 1;
}

// You don't necessarily need to copy binary data out, but just to show where it is:
var binary = new byte[binaryLength];
Buffer.BlockCopy(buf, offset, binary, 0, binaryLength);

line.TrimEnd('\r')Window スタイルの行末が必要な場合は、を実行することもできます。

于 2013-03-25T12:13:48.610 に答える