Sangeetha
Sangeetha

Reputation: 591

File handling in c#

In my c# application, when i upload a file , it needs to be converted to temp file and store in a temporary folder then read the temp file as image find its height width every thing and later stores in databse.I am getting error when I read the temp file as image, as Out of Memory, below is my entire code.

string img = System.Windows.Forms.Application.StartupPath +@"\"+ path;
//in path .png file is accessed.
            string filename = Path.GetFileName(img);
            string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
            string IEPath=internetCache+@"\tmp";
            if (!Directory.Exists(IEPath))
                Directory.CreateDirectory(IEPath);


            FileInfo fi = new FileInfo(img);
            FileStream fs = fi.OpenRead();
            //lResult = URLDownloadToFile(0, img.src, TempFolder & strFileName, 0, 0)
            Stream stream = fs;
            byte[] buffer = new byte[fs.Length];
            stream.Seek(273, SeekOrigin.Begin);
            stream.Read(buffer, 0, (int)buffer.Length);

            string tempfile = Path.Combine(IEPath, Math.Abs(filename.GetHashCode()) + ".tmp");
            File.WriteAllBytes(tempfile, buffer);
            fs.Close();
            stream.Close();

            string _contentType = "application/octet-stream";
            FileType Type = FileType.png;
            string MimeType = "image/png";
            FileStream fst = new FileStream(tempfile, FileMode.Open);
            Image _image = System.Drawing.Image.FromStream(fst, true, true);

The last line where I am getting the exception as out of memory. Please help me to find a solution.

Upvotes: 0

Views: 1520

Answers (2)

jjchiw
jjchiw

Reputation: 4455

I just followed the instructions of the question:

  1. read some file
  2. Copy the file to a temp file
  3. Read as image
  4. Get width & height

    var bytes = File.ReadAllBytes(@"C:\temp\duck.jpg");
    var temp = Path.GetTempFileName();
    File.WriteAllBytes(temp, bytes);
    
    var img = Image.FromFile(temp);
    Console.WriteLine ("width: {0}, height: {0}", img.Width, img.Height);
    

Upvotes: 0

spender
spender

Reputation: 120518

I'd venture that the stream you are reading is corrupted (perhaps because you remove the leading 273 bytes).

Upvotes: 2

Related Questions