Has nothing direct, do another classe
or use the example below:
Put a List of Fileinfo:
List<FileInfo> files = new List<FileInfo>();
Add items from 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 pass the list List<FileInfo> files
for List<Attachment> AttachmentList
:
foreach(var item in files)
{
AttachmentList.Add(new Attachment(item.FullName));
}
To transform the size of long
in Kb
or Mb
put 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 question user.
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 in your form two variables:
AttachmentAndFileInfoList attFileInfo = new AttachmentAndFileInfoList();
IList<Attachment> attachmentList;
Adding items and showing in 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 Attachment list ready
private void button2_Click(object sender, EventArgs e)
{
attachmentList = attFileInfo.AttachmentToList();
}
References:
Attachment class
Openfiledialog class
Fileinfo class
Windows Forms ?
– user46523
Hello John, sorry I didn’t put, that’s right Winforms
– William