João Silva
João Silva

Reputation: 581

C# should I close the streams when im using "using"?

I have a service running on a server that zip files and I notice that each day the memory consumed increases, when I deployed it on the server it was consuming 3.6Mb, today, 3 months later it was consuming 180Mb.

This is part of the code that I'm using:

for (i = 0; i < files.Count; i++)
{
    try
    {
        if (File.Exists(@dir + zipToUpdate) && new FileInfo(@dir + zipToUpdate).Length < 104857600)
        {
            using (FileStream zipToOpen = new FileStream(@dir + zipToUpdate, FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update, false))
                {

                    if (File.GetCreationTime(@dir + files.ElementAt(i)).AddHours(FileAge) < DateTime.Now)
                    {
                        ZipArchiveEntry fileEntry = archive.CreateEntry(files.ElementAt(i));
                        using (BinaryWriter writer = new BinaryWriter(fileEntry.Open()))
                        {
                            using (FileStream sr = new FileStream(@dir + files.ElementAt(i), FileMode.Open, FileAccess.Read))
                            {
                                byte[] block = new byte[32768];
                                int bytesRead = 0;
                                while ((bytesRead = sr.Read(block, 0, block.Length)) > 0)
                                {
                                    writer.Write(block, 0, bytesRead);
                                    block = new byte[32768];
                                }
                            }
                        }
                        File.Delete(@dir + files.ElementAt(i));
                    }
                }
            }
        }
        else
        {
            createZip(files.GetRange(i, files.Count-i), dir + "\\", getZipName(dir, zipToUpdate));
            return;
        }
    }
    catch (Exception ex)
    {

        rootlog.Error(string.Format("Erro Run - updateZip: {0}", ex.Message));
    }
}

The creation of the zip or the update are similar so there is no point in paste both codes.

I do a recursive call of this for the folders inside and the service runs once each hour.

So, my question is if all these streams is what is making my memory usage increase month after month or if it can be something else.

Upvotes: 1

Views: 82

Answers (1)

Mureinik
Mureinik

Reputation: 311798

The using statement takes care of closing the IDisposable object that it opens. This is not the source of the potential memory leak you're observing.

Upvotes: 1

Related Questions