Do not have anything straight, make another classe
or use the example below:
Place a List FileInfo :
List<FileInfo> files = new List<FileInfo>();
Add the items to OpenFileDialog :
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
files.Add(new FileInfo(openFileDialog1.FileName));
}
dataGridView1.DataSource = files.Select(c => new {
c.Name,
c.Length,
c.FullName,
LengthDescription = fileInfoTam(c.Length)
}).ToList();
At the end you move from the list List<FileInfo> files
to List<Attachment> AttachmentList
:
foreach(var item in files)
{
AttachmentList.Add(new Attachment(item.FullName));
}
To transform the size of long
into Kb
or Mb
place this method either in a class or in the form code itself:
public string fileInfoTam(long length)
{
double value = (length / 1024);
string label = "Kb";
if ((length / 1024) > 1024)
{
value = ((length / 1024) / 1024);
label = "Mb";
}
return string.Format("{0} {1}", Math.Round(value, 4), label);
}
Reference: code given by the user of the question .
Another way:
Create these two classes in your project:
public class AttachmentAndFileInfo
{
public Attachment Attachment { get; private set; }
public FileInfo FileInfo { get; private set; }
public AttachmentAndFileInfo(string fileName)
{
if (!File.Exists(fileName))
throw new Exception("Inválid path");
Attachment = new Attachment(fileName);
FileInfo = new FileInfo(fileName);
}
}
public class AttachmentAndFileInfoList: List<AttachmentAndFileInfo>
{
public IList ToSelectList()
{
return this.Select(c => new
{
c.Attachment.Name,
Path = c.FileInfo.FullName,
Length = c.FileInfo.Length,
LengthDescription = fileInfoTam(c.FileInfo.Length)
})
.ToList();
}
public IList<Attachment> AttachmentToList()
{
return this.Select(c => c.Attachment).ToList();
}
public IList<FileInfo> FileInfoToList()
{
return this.Select(c => c.FileInfo).ToList();
}
internal string fileInfoTam(long length)
{
double value = (length / 1024);
string label = "Kb";
if ((length / 1024) > 1024)
{
value = ((length / 1024) / 1024);
label = "Mb";
}
return string.Format("{0} {1}", Math.Round(value, 2), label);
}
}
Now create two variables in your form:
AttachmentAndFileInfoList attFileInfo = new AttachmentAndFileInfoList();
IList<Attachment> attachmentList;
Adding the items and showing in the DataGridView
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
attFileInfo.Add(new AttachmentAndFileInfo(openFileDialog1.FileName));
}
dataGridView1.DataSource = attFileInfo.ToSelectList();
}
Getting the Ready Attachment List
private void button2_Click(object sender, EventArgs e)
{
attachmentList = attFileInfo.AttachmentToList();
}
References:
Class Attachment
OpenFileDialog Class
FileInfo Class