Вот мой код. Я пытаюсь заменить изображение из одной папки другим изображением в другой папке, сохраняя при этом его имя файла.
Я получаю содержимое папки с помощью dataGridView
Я загружаю изображение из выбранной ячейки прямо в picturebox
Я использую:
File.Copy(Source, Destination,true);
Чтобы скопировать мой файл, я удалил ВСЕ, чтобы он не использовался процессом.
Мой полный проект (с комментариями):
private void Form1_Load(object sender, EventArgs e)
{
//Get content of the DESTINATION files on a specific folder and put it into a dataGridView1
string[] files = Directory.GetFiles(@Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Black Desert\\FaceTexture", "*", SearchOption.TopDirectoryOnly);
DataTable table = new DataTable();
table.Columns.Add("File Name");
for (int i = 0; i < files.Length; i++)
{
FileInfo file = new FileInfo(files[i]);
table.Rows.Add(file.Name);
}
dataGridView1.DataSource = table;
//Get content of the SOURCE files on a specific folder and put it into a dataGridView2
string[] files2 = Directory.GetFiles(@"Face Texture", "*");
DataTable table2 = new DataTable();
table2.Columns.Add("File Name");
for (int i = 0; i < files2.Length; i++)
{
FileInfo file = new FileInfo(files2[i]);
table2.Rows.Add(file.Name);
}
dataGridView2.DataSource = table2;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Black Desert\\FaceTexture\\" + dataGridView1.SelectedCells[0].Value.ToString()).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len = len / 1024;
}
string result = String.Format("{0:0.##} {1}", len, sizes[order]);
//We get the picturebox to show which file we selected in the cell (datagridview1)
pictureBox1.Image = Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Black Desert\\FaceTexture\\" + dataGridView1.SelectedCells[0].Value.ToString());
LblFileName1.Text = dataGridView1.SelectedCells[0].Value.ToString();
//We have the full path here
LblFilePath1.Text = (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Black Desert\\FaceTexture\\" + dataGridView1.SelectedCells[0].Value.ToString());
LblFileSize1.Text = result;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
button1.Enabled = true;
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo("Face Texture\\" + dataGridView2.SelectedCells[0].Value.ToString()).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len = len / 1024;
}
string result = String.Format("{0:0.##} {1}", len, sizes[order]);
//We get the picturebox to show which file we selected in the cell (datagridview2)
pictureBox2.Image = Image.FromFile("Face Texture\\" + dataGridView2.SelectedCells[0].Value.ToString());
LblFileName2.Text = dataGridView2.SelectedCells[0].Value.ToString();
//We have the full path here
LblFilePath2.Text = "Face Texture\\" + dataGridView2.SelectedCells[0].Value.ToString();
LblFileSize2.Text = result;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Get store into a string both paths before disposing them
string Source = LblFilePath1.Text;
string Destination = LblFilePath2.Text;
pictureBox1.Dispose();
pictureBox2.Dispose();
dataGridView1.Dispose();
dataGridView2.Dispose();
LblFileName1.Dispose();
LblFileName2.Dispose();
LblFilePath1.Dispose();
LblFilePath2.Dispose();
LblFileSize1.Dispose();
LblFileSize2.Dispose();
File.Copy(Source, Destination, true);
MessageBox.Show(Source + Destination);
}
catch (Exception ex2)
{
//Eh, used by the process ..
MessageBox.Show(ex2.Message);
}
}
Привет, Ганс, спасибо, что сработало. В чем разница между Picturebox1.Dispose();
и Picturebox1.Image.Dispose();
Объект изображения, созданный с помощью Image.FromFile(), должен быть удален после использования, чтобы снять блокировку с файла. PictureBox не может сделать это за вас, он не знает, откуда взялось изображение.
Вы хотите избавиться от объекта изображения, а не от объекта PictureBox.
Поэтому pictureBox.Image.Dispose()
решит проблему.
Итак, PictureBox имеет класс свойств изображение, который имеет метод Dispose()
pictureBox1.Image.Dispose() и т. д.