Ошибка нулевого значения объекта ("System.InvalidOperationException" в mscorlib.dll ) - C#
Формулировка задачи:
Всем привет.
Вылетает ошибка при запаковке файла GZip'ом. При том нестабильно и нерегулярно. Проверьте плиз на своих машинах:
Листинг программы
- using System;
- using System.IO;
- using System.IO.Compression;
- using System.Threading;
- namespace Compress_Decompress
- {
- class GZipTest
- {
- static int BufferSize = 2048*2048; //!!!!!!
- const int multithread= 8;//количество потоков
- public static void WriteBlock(GZipStream inStream,int read, byte[] buffer) //запись в архив из входного блока
- {
- try
- {
- Console.Write('-');
- inStream.Write(buffer, 0, read);
- }
- catch (Exception ex)
- {
- Console.WriteLine("ERROR: " + ex.Message);
- // error = true;
- }
- }
- public static void WriteBlockCompressed(FileStream inStream, int read, byte[] buffer)//запись архивного блока в выходной файл
- {
- Console.Write('-');
- inStream.Write(buffer, 0, read);
- }
- public static void Compress(string inFileName, string outFileName, bool error)//путь к входному файлу, путь к выходному файлу, флаг
- {
- try
- {
- using (FileStream inFile = new FileStream(inFileName, FileMode.Open))//инициализация входного файла
- {
- using (FileStream comp = new FileStream(outFileName, FileMode.Create, FileAccess.Write))//инициализация выходного файла
- {
- //
- // ПРИ РАБОТЕ С КОНСОЛЬЮ WINDOWS
- // ОБЯЗАТЕЛЬНО УКАЗЫВАЕМ ПОЛНЫЙ ПУТЬ И РАСШИРЕНИЕ ДЛЯ ВХОДНЫХ И ВЫХОДНЫХ ФАЙЛОВ!!!!
- //
- using (GZipStream inStream = new GZipStream(comp, CompressionMode.Compress))//буферный поток сжатия
- {
- int read = 0;
- byte[] buffer = new byte[BufferSize];
- while ((inFile.Length > inFile.Position)||(read!=0))
- {
- Thread[] thread = new Thread[multithread];//множим потоки
- for (int i = 0; i < multithread; i++)
- {
- read = inFile.Read(buffer, 0, BufferSize);
- Console.Write("|{0}", i);//смотрим на флаг смены потоков
- thread[i] = new Thread(() =>
- WriteBlock(inStream, read, buffer)
- );
- thread[i].Start();
- // thread[i].Join();
- }
- // thread[multithread].Join();
- for(int i=0;i<multithread;i++)
- {
- thread[multithread-i-1].Join();
- }
- }
- inStream.Close(); //!!!!!!
- }
- comp.Close();
- }
- inFile.Close();
- }
- error = false;
- Console.WriteLine(" finished packing. ");
- }
- catch (Exception ex)
- {
- Console.WriteLine("ERROR: " + ex.Message);
- error = true;
- }
- }
- public static void Decompress(string inFileName, string outFileName, bool error) //путь к входному файлу, путь к выходному файлу, флаг
- {
- try
- {
- FileStream inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);//инициализация входного файла
- {
- using (GZipStream decomp = new GZipStream(inFile, CompressionMode.Decompress))//инициализация буфера распаковки
- {
- //
- // ПРИ РАБОТЕ С КОНСОЛЬЮ WINDOWS
- // ОБЯЗАТЕЛЬНО УКАЗЫВАЕМ ПОЛНЫЙ ПУТЬ И РАСШИРЕНИЕ ДЛЯ ВХОДНЫХ И ВЫХОДНЫХ ФАЙЛОВ!!!!
- //
- using (FileStream outStream = new FileStream(outFileName, FileMode.Create, FileAccess.Write))//инициализация выходного файла
- {
- int read;
- byte[] buffer = new byte[BufferSize];
- while (inFile.Length > inFile.Position)
- {
- Thread[] thread = new Thread[multithread];
- for (int i = 0; i < multithread; i++)
- {
- read = decomp.Read(buffer, 0, BufferSize);
- Console.Write("|{0}", i);//смотрим на флаг смены потоков
- thread[i] = new Thread(() =>
- WriteBlockCompressed(outStream, read, buffer)
- );
- thread[i].Start();
- }
- foreach (Thread trd in thread)//закрываем все потоки
- {
- trd.Join();
- }
- }
- outStream.Close();
- }
- decomp.Close();
- }
- inFile.Close();
- }
- Console.WriteLine(" finished unpacking. ");
- error = false;
- }
- catch (Exception ex)
- {
- Console.WriteLine("ERROR: " + ex.Message);
- error = true;
- }
- }
- }
- class Program
- {
- static string GZip, fIN, fOUT;
- static bool error = true,
- flag = true;
- public static void Main(string[] args)//параметры для командной строки должны быть закомментированы для отладки!!!!
- {
- DateTime dold = DateTime.Now;
- /* try
- {
- GZip = args[0]; //во время работы с консолью раскомментировать GZip, fIN, fOUT!!!!
- fIN = args[1];
- fOUT = args[2];
- }
- catch (Exception ex)
- {
- Console.WriteLine("ERROR: " + ex.Message+"|| Неверно введены параметры.");
- error = true;
- }*/
- try
- {
- Console.CancelKeyPress += delegate //ловим ctrl+c
- {
- GC.Collect(); //чистим мусор
- flag = false;
- };
- while ((true)&(flag))
- {
- GZip = "compress"; //
- fIN = "d:/test.avi"; //тестовые значения для отладки!!!!!
- fOUT = "d:/test.avi.gz"; //
- if (GZip == "compress")
- {
- Console.WriteLine("packing: ");
- GZipTest.Compress(fIN, fOUT, error);
- }
- else if (GZip == "decompress")
- {
- Console.Write("unpacking: ");
- GZipTest.Decompress(fIN, fOUT, error);
- }
- flag = false;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("ERROR: " + ex.Message);
- error = true;
- }
- TimeSpan sp = DateTime.Now - dold;
- Console.WriteLine("press Enter to terminate! CODE {0}", error ? "1" : "0");
- Console.WriteLine("completed in {0} secs",sp);
- Console.ReadLine();
- }
- }
- }
Решение задачи: «Ошибка нулевого значения объекта ("System.InvalidOperationException" в mscorlib.dll )»
textual
Листинг программы
- public static void Compress(string inFileName, string outFileName)//путь к входному файлу, путь к выходному файлу
- {
- try
- {
- using (FileStream inFile = new FileStream(inFileName, FileMode.Open))//инициализация входного файла
- {
- using (FileStream outFile = new FileStream(outFileName, FileMode.Create, FileAccess.Write))//инициализация выходного файла
- {
- //
- // ПРИ РАБОТЕ С КОНСОЛЬЮ WINDOWS
- // ОБЯЗАТЕЛЬНО УКАЗЫВАЕМ ПОЛНЫЙ ПУТЬ И РАСШИРЕНИЕ ДЛЯ ВХОДНЫХ И ВЫХОДНЫХ ФАЙЛОВ!!!!
- //
- using (GZipStream inGZip = new GZipStream(outFile, CompressionMode.Compress))//буферный поток сжатия
- {
- int i = 0, j = 0;
- int[] read = new int[multithread];
- byte[] buffer = new byte[BufferSize];
- Thread[] thread = new Thread[multithread];
- Thread[] thread_ = new Thread[multithread];
- var mem = new MemoryStream();
- while ((inFile.Length - inFile.Position) > BufferSize)
- {
- for (j = 0; (j < multithread) && ((inFile.Length - inFile.Position) > BufferSize); j++)
- {
- thread[j] = new Thread(() =>
- {
- read[j] = inFile.Read(buffer, 0, BufferSize);
- Console.Write("- {0} -", j);
- });
- thread[j].Start();
- thread[j].Join();
- thread_[j] = new Thread(() =>
- {
- inGZip.Write(buffer,0, read[j]);
- Console.Write("|");
- // Thread.Sleep(1100);
- });
- thread_[j].Start();
- thread_[j].Join();
- }
- for (i = 0; i < j; i++)
- {
- thread[i].Join();
- }
- }
- inGZip.Write(buffer, 0, inFile.Read(buffer, 0, BufferSize));
- inGZip.Close(); //!!!!!!
- }
- outFile.Close();
- }
- inFile.Close();
- error = false;
- Console.WriteLine(" finished packing. ");
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("ERROR: " + ex.Message);
- error = true;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д