سؤال

يتلقى عميل TCP الخاص بي صورة داخل حزمة. يتم ضغط الصورة مع Zlib.The المهمة هي إلغاء ضغط الصورة ووضعها في النموذج.

أخطط لحفظ الصورة المضغوطة في الدليل الحالي، إلغاء ضغطها وتحميل الملف DemoMpressed على النموذج.

المشكلة الأولى تأتي مع حفظ الملف (مضغوط). يمكن ل ZLIB حفظها إلغاء ضغطها.

يحمل الرمز أدناه الملف المضغوط ويحفظه بعد الضغط.

    private void decompressFile(string inFile, string outFile)
    {
        System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
        zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream);
        System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open);          
        try
        {
            CopyStream(inFileStream, outZStream);
        }
        finally
        {
            outZStream.Close();
            outFileStream.Close();
            inFileStream.Close();
        }
    }

    public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
    {
        byte[] buffer = new byte[2000];
        int len;
        while ((len = input.Read(buffer, 0, 2000)) > 0)
        {
            output.Write(buffer, 0, len);
        }
        output.Flush();
    }

كيفية تمرير صفيف البايت [] مباشرة إلى هذه الوظيفة؟ أخطط لإنقاذها كضغط ثم استدعاء الوظيفة مع موقع الملف المضغوط، لكنني لا أعرف كيفية حفظ ملف من صفيف بايت [] ولا طريقة لتمرير صفيف البايت [] كملف الإدخال.

أي مساعدة سوف تكون محل تقدير كبير.

شكرا.

هل كانت مفيدة؟

المحلول

استخدم STATION SYSTEM.IO.FILE.WRITEALLBYTES (مسار سلسلة، بايت [] بايت).

byte[] buffer = new byte[200];
File.WriteAllBytes(@"c:\data.dmp", buffer);

نصائح أخرى

public static void SaveFile(this Byte[] fileBytes, string fileName)
{
    FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
    fileStream.Write(fileBytes, 0, fileBytes.Length);
    fileStream.Close();
}

بالإضافة إلى ما ذكره الجميع بالفعل، أود أيضا أن أقترح عليك استخدام بنود "باستخدام" لأن جميع هذه الكائنات تنفذ ناهتة.

using(FileStream outFileStream = new ...)
using(ZOutputStream outZStream = new ...)
using(FileStream inFileStream = new ...)
{
    CopyStream(inFileStream, outZStream);
}

عصا مجموعة البايت التي تلقيتها في MemoryStream وضغط / إلغاء ضغطه على الطاير دون استخدام ملفات مؤقتة.

يمكنك تجربة هذا الرمز

 private void t1()
    {
        FileStream f1 = new FileStream("C:\\myfile1.txt", FileMode.Open);
        int length = Convert.ToInt16(f1.Length);
        Byte[] b1 = new Byte[length];
        f1.Read(b1, 0, length);
        File.WriteAllBytes("C:\\myfile.txt",b1);
        f1.Dispose();
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top