C# unload image from imagebox - c#

I have a method whit the following logic:
I delete all files from input and output folders
user selects an initial picture
this pictures as being assigned to imageBox1
picture is being copied to the folder input
magic happens to picture and I put it to the folder output
new picture from output is beign assigned to imageBox2
Here is where problem starts. When users wants to repeat operation imagebox1 and imagebox2 do have pictures assigned to them. And the step #0 failswith error
The process cannot access the file '03933.tiff' because it is being used by another process.
What I was trying is :
private void CopyImage_Click(object sender, EventArgs e)
{
string currentPath = Directory.GetCurrentDirectory();
string pathInput = currentPath + "\\Input";
string pathOutput = currentPath + "\\Output";
if (pictureBoxInput.Image != null) {
pictureBoxInput.Image = null;
pictureBoxInput.Dispose();
}
if (pictureBoxOutput.Image != null) {
pictureBoxOutput.Image = null;
pictureBoxOutput.Dispose();
}
System.IO.DirectoryInfo di = new DirectoryInfo(pathInput + "\\");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
System.IO.DirectoryInfo dia = new DirectoryInfo(pathOutput + "\\");
foreach (FileInfo file in dia.GetFiles())
{
file.Delete();
}
But still having the same error when program tries to delete files.

I would suggest changing:
if (pictureBoxInput.Image != null) {
pictureBoxInput.Image = null;
pictureBoxInput.Dispose();
}
to:
if (pictureBoxInput.Image != null) {
var existingFile = pictureBoxInput.Image;
pictureBoxInput.Image = null;
existingFile?.Dispose();
}
and the same for pictureBoxOutput
The issue is that your existing code is disposing the wrong thing - you are disposing the PictureBox rather than the Image (and the Image is the thing that is holding the file lock).

Related

ZipArchive problem with Access to the process

I try to do a function which of the files from the zip file will take two values ​​and update them in the GUI.
the problem is that i get exception about access to the file.
System.IO.IOException: 'The process cannot access the file 'C:\work\RasMol.zip' because it is being used by another process.'
public void ReplaceEntry(string fileName)
{
var infoList = new List<RPPXFileEntry>();
{
ZipArchive Archive = ZipFile.Open(this.sourcePath, ZipArchiveMode.Update);
//exception in this place
foreach (ZipArchiveEntry entry in Archive.Entries)
{
var rppxEntry = new RPPXFileEntry();
if (entry.Name == fileName)
{
rppxEntry.Modify = entry.LastWriteTime;
rppxEntry.Size = entry.Length;
infoList.Add(rppxEntry);
}
}
this.AllEntries = infoList;
}
}
someone know how to deal with it?

C# Copy file from Android to PC

I need to copy a bunch of files from an Android phone to the PC.
It doesn't work the normal way, the PC is super slow and crashes all the time for some reason.
I want to copy it file by file.
My problem is that if I use Directory.GetFiles("Path") or DirectoryInfo.GetFiles("Path") it does add the persistant Datapath to the path for some reason and I get this error message:
DirectoryNotFoundException: Could not find a part of the path 'D:\GameDev\CopyProgram\Dieser PC\HTC One M9\Interner gemeinsamer Speicher'.
The actual path is only "Dieser PC\HTC One M9\Interner gemeinsamer Speicher", is there any way to do that?
//there is an input field where you can enter the paths
(copy it from the explorer)
[SerializeField]
private string copyFrom = "Dieser PC\HTC One M9\Interner gemeinsamer Speicher";
[SerializeField]
private string copyTo = "C:\Users\Nutzer\Desktop\Neuer Ordner";
private bool running = false;
public void Copy()
{
if(running == true)
{
return;
}
running = true;
//Start
//Get all items from folder
DirectoryInfo d = new DirectoryInfo(copyFrom);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string currentFile = file.DirectoryName + "/" + file.Name;
string copyFile = copyTo + "/" + file.Name;
try
{
if (file == null)
continue;
File.Copy(currentFile, copyFile, true);
}
catch (Exception)
{
throw;
}
}
//End
running = false;
}
I searched through the internet and could not find a solution, please help!
Thanks!

What is the best way to copy a list of files with these variable filenames using Path.Combine

I have source directories c:\source\yyyy-MM-dd where yyyy-MM-dd represents a range of dates, and a destination directory e:\destination. I need to look for multiple filenames in each date directory in that range of dates and only copy (filenameA*.*, filenameB*.*, filenameC*.*). I then need to create the date directories from the range of dates and copy the associated files found into their respective directories.
I'm using two datetimepickers to get the range of dates. I have that foreach logic working fine. I'm only struggling with the best way to use Path.Combine to create the destination folders and copy each of the files. I think I'm doing unnecessary work in my existing code, and I keep confusing myself:
private async void ProcessFiles()
{
// create a list of topics
var topics = topicsBox.CheckedItems.Cast<string>().ToList();
// create a list of source directories based on date range
var directories = new List<string>();
var folders = new List<string>();
for (DateTime date = dateTimePicker1.Value.Date;
date.Date <= dateTimePicker2.Value.Date;
date = date.AddDays(1))
{
var dateDir = _tracePath + #"\" + date.ToString("yyyy-MM-dd") + #"\";
directories.Add(dateDir);
folders.Add(#"\" + date.ToString("yyyy-MM-dd") + #"\");
}
// create a list of source files to copy and destination
foreach (var path in directories)
{
var path1 = path;
try
{
foreach (var files2 in folders)
{
var destPath = textBox1.Text + #"\" + textBox4.Text + files2;
foreach (var files in topics)
{
if (!Directory.Exists(path1))
{
toolStripStatusLabel1.ForeColor = Color.Red;
toolStripStatusLabel1.Text = ("Could not find \"" + path1 +
"\" Check start and end date.");
}
else
{
foreach (
string sourcePath in
Directory.EnumerateFiles(path1, files + "*.*", SearchOption.AllDirectories))
{
var filename = Path.GetFileName(sourcePath); // get each filename in source directory
var fullDestPath = Path.Combine(destPath, filename); // create the destination folder name
Directory.CreateDirectory(sourcePath.Replace(sourcePath, destPath)); // create the destination folder
// copy the files to the temp folder asynchronously
using (FileStream SourceStream = File.Open(sourcePath, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(fullDestPath))
{
xferBtn.Enabled = false;
toolStripStatusLabel1.ForeColor = Color.Green;
toolStripStatusLabel1.Text = "Copying " + sourcePath;
await SourceStream.CopyToAsync(DestinationStream);
toolStripStatusLabel1.Text = "Copying complete!";
}
}
}
}
}
}
}
catch (Exception e)
{
}
}
}
To start, it may be easier to break things apart into separate methods to keep track of tasks. I find this to be easier when doing multiple tasks in one method. I just created a simple test to copy files from a source to destination. This won't match your logic, but it may lead you in the right direction. When you enumerate over files, you get an IEnumerable object to work with. You can use that to just iterate over your file paths. Also, you have a DirectoryInfo object you can use to check for directory creation before copying. I also did not follow your logic with source/destination stream, but instead just used the System.File.IO.Copy method that show how Path.Combine works. This is an easy way to combine say a path to a directory and a file without concatenation. Its basically a string.Format("{0}", somthingToAppend).
private void BtnProcess_Click(object sender, EventArgs e)
{
// create a list of source directories based on date range
List<string> sourceDirectories = new List<string>();
List<string> destDirectories = new List<string>();
sourceDirectories.Add("C:\\Users\\Eric\\Desktop\\Dir1");
sourceDirectories.Add("C:\\Users\\Eric\\Desktop\\Dir2");
destDirectories.Add("C:\\Users\\Eric\\Desktop\\Dest1");
destDirectories.Add("C:\\Users\\Eric\\Desktop\\Dest2");
// create a list of source files to copy and destination
foreach (var path in sourceDirectories)
{
if (!Directory.Exists(path))
{
//Error message here if path does not exist or continue with the next path
continue;
}
try
{
IEnumerable<string> paths = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories);
DirectoryInfo destPathInfo = Directory.CreateDirectory(destDirectories[0]); // create the destination folder
if (destPathInfo.Exists)
{
foreach (var p in paths)
{
string destination = System.IO.Path.Combine(destDirectories[0], System.IO.Path.GetFileName(p));
System.IO.File.Copy(p, destination);
}
destDirectories.RemoveAt(0);
}
}
catch (Exception ex)
{
}
}
}

Delete a folder whose items are open in browser

sdel = Server.MapPath("~/Media_Extracted_Content" + "/" + sfolder);
Directory.Delete(sdel,true);
'sfolder' contains different sub folder and all sub folder have contains different items. All items like image file, audio file, video file opened in browser .I am copying that items from this existing location to new location and after that I have to delete this directory from my system. Whenever I am trying to to this it shows error that Directory is not empty. Also, when I am trying to delete individual items from sub folder it is showing error that this file is being used by another process. Please help me.
I think at Server or at Hosting you have not given the permision to the folder which are, allow READ and WRITE to the Folder.
Please Try This Two FUNCTION/Method.
You only have to do is paste both function in class file(eg class1.cs).
In (aspx.cs)Assign Value to source and destination
For Example source = Server.MapPath("~/Media_Extracted_Content/" + sourcefolder);
destination = Server.MapPath("~/Media_Extracted_Content/" + destinationfolder);
And Call classobject.MoveFiles(source, destination,true);
public void createfolder(string directorypath)
{
// CREATE folder
try
{
Directory.CreateDirectory(directorypath);
}
catch (Exception ex)
{ }
}
public void MoveFiles(string source, string destination, bool overwrite)
{
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(source);
System.IO.DirectoryInfo outputDir = new System.IO.DirectoryInfo(destination);
try
{
if ((inputDir.Exists))
{
if (!(outputDir.Exists))
{
createfolder(destination);
// outputDir.Create();
}
//Get Each files and copy
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if ((overwrite))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), true);
}
else
{
if (((System.IO.File.Exists(System.IO.Path.Combine(outputDir.FullName, file.Name))) == false))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), false);
}
}
System.IO.File.Delete(file.FullName);
}
//Sub folder access code
System.IO.DirectoryInfo dir = null;
foreach (System.IO.DirectoryInfo subfolderFile in inputDir.GetDirectories())
{
dir = subfolderFile;
//Destination path
if ((dir.FullName != outputDir.ToString()))
{
MoveFiles(dir.FullName, System.IO.Path.Combine(outputDir.FullName, dir.Name), overwrite);
}
System.IO.Directory.Delete(dir.FullName);
}
}
}
catch (Exception ex)
{
}
}

Web API handle uploaded files for delete

ok I have this code that handle a file been upload through a simple web form
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(#"C:\inetpub\wwwroot\myapp\Images");
//var provider = new MultipartFormDataStreamProvider(#"C:\inetpub\wwwroot\myapp\Images");
var Image = "";
var Dir = "";
var CurrentPath = "";
string UploadType = "";
string ImageName = "";
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key == "uploadType") UploadType = val;
if (key == "imageName") ImageName = val;
//Trace.WriteLine(string.Format("{0}: {1}", key, val));
}
}
foreach (MultipartFileData file in provider.FileData)
{
//Debug.WriteLine(file.Headers.ContentDisposition.FileName);
//Debug.WriteLine("Server file path: " + file.LocalFileName);
Image = Path.GetFileName(file.LocalFileName);
Dir = Path.GetDirectoryName(file.LocalFileName);
CurrentPath = file.LocalFileName;
}
if (UploadType == "update")
{
File.Delete(Dir + "\\" + Image);
File.Move(CurrentPath, Dir + "\\" + Image);
Imagen = ImageName;
}
return Request.CreateResponse(HttpStatusCode.OK, Image);
as some docs mention using await will cause the read process to be async, my problem is that I need to know when the file has been saved into the folder cause I want to delete it after if the UploadType form field is == to update, but it seems like when try this line
File.Delete(Dir + "\\" + Image);
the image is has not been saved yet and I got an error that the image don't exist, so my question is, how I can tell or be sure the image is ready in the dir? how can I tell the async process ends, thanks for any help on this!!
File.Exists is the method you should use.
Aside You should be using Path.Combine instead of building the path with concatenation.

Categories