Example #1
0
        private static void DumpAttachment(string dir, AttachmentBase attachment)
        {
            string name = null;

            if (!string.IsNullOrEmpty(attachment.ContentType.Name))
            {
                name = attachment.ContentType.Name;
            }
            else
            {
                name = attachment is AlternateView ? "alternate-view" : "attachment";
                string ext = MimeUtility.GetFileExtensionFromMediaType(attachment.ContentType.MediaType);
                if (ext == "eml")
                {
                    name = "attached-message";
                }
                name = string.Format(name + "." + ext);
            }

            int    i         = 1;
            string shortname = null;

            while (File.Exists(dir + Path.DirectorySeparatorChar + name))
            {
                FileInfo fi = new FileInfo(name);
                if (null == shortname)
                {
                    shortname = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);
                }

                name = string.Format("{0} ({1}){2}", shortname, i, fi.Extension);
                i++;
            }

            using (Stream stream = File.Create(dir + Path.DirectorySeparatorChar + name))
            {
                byte[] buffer = new byte[32768];
                while (true)
                {
                    int read = attachment.ContentStream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                    {
                        break;
                    }
                    stream.Write(buffer, 0, read);
                }
            }
        }