IOException when moving an image file - c#

private void MoveFile(string destination, string imagePath)
{
try
{
string source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["TempImagePath"]);
string[] resizedImage = imagePath.Split('.');
//string compressedImagePath = resizedImage[0] + "_compress." + resizedImage[1];
string thumbnail150Name = resizedImage[0] + "_thumbnail." + resizedImage[1];
string mediumPhoto300Name = resizedImage[0] + "_mediumPhoto." + resizedImage[1];
string largePhotoName = resizedImage[0] + "_largePhoto." + resizedImage[1];
//Move thumbnail
if (System.IO.File.Exists(source + "\\" + thumbnail150Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + thumbnail150Name, destination + "\\" + thumbnail150Name);
}
//Move medium sized photo
if (System.IO.File.Exists(source + "\\" + mediumPhoto300Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + mediumPhoto300Name, destination + "\\" + mediumPhoto300Name);
}
//Move large photo
if (System.IO.File.Exists(source + "\\" + largePhotoName))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + largePhotoName, destination + "\\" + largePhotoName);
}
//Move original
if (System.IO.File.Exists(source + "\\" + imagePath))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + imagePath, destination + "\\" + imagePath);
}
}
catch (Exception ex)
{
BgLogger.FileLogger.LogError("In private method : MoveFile(string, string), On server : " + Dns.GetHostName() + " At : " + DateTime.Now, ex).Wait();
}
}
I am using this code while moving an image file. But I am getting the following exception
System.IO.IOException: The process cannot access the file because it
is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalMove(String sourceFileName, String
destFileName, Boolean checkHost) at
BgPortal.Controllers.DriverController.MoveFile(String destination,
String imagePath)
https://u3307993.ct.sendgrid.net/wf/open?upn=mzyvlCvUM5odb-2FP3IS9fxavC9Nq-2BVU-2BlgxLxmreq6Qi5SziY4JAfC5R720TrBfTXj7GdvSOgEG2Qeq-2BGKm-2FwWmPOrbAem6UFnvcBKca-2FzIM3XkXg0dHdke9rhjcAKDqtd0MJQCnmyIN-2Fi-2FXbgygtnXFNxuEuwts4hybPsnVR72PsfW4L6YZ32pnlEuwGMF-2Fcg0S8f8Y7UOBHwDMzh1BgJnhqO9i5dgS9LRZytY4n6TNCt37JAtdi5EOj8OxBqhan
This exception occurs very randomly.
Can anyone help me with this?

The exception is thrown because the file you are trying to move is open by your program or another process. Make sure that you are always closing the file after you finish processing it. Particularly, make sure that you always call Close or Dispose on all FileStream objects when they are no longer needed.
If the file is open by another process (for example by another user) then you can wait for some time and retry moving the file.

Related

Error with database file path in project with many databases

I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}
Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.

How Change name file after Creation in startup folder?

I With Code my application added to startup
how I can after Creation File (filename + ".url") Change To (filename + ".exe")
static string filename = "troj";
public static string tempure = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + filename + ".exe";
public static string tempurepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\";
public static void addtostart()
{
try
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (System.IO.File.Exists(deskDir + "\\" + filename + ".url")) return;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(deskDir + "\\" + filename + ".url"))
{
string app = tempure;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
catch
{

File.Move is adding a padlock to file image

I'm making a bit of code in Visual Studio to sort my music files (.m4a).
I have a listbox with a list of files on my desktop.
My code loops through each file.
Example files:
[Eminem] Not alone.m4a
[Imagine Dragons] Radioactive.m4a
[Dragon Force] Through Fire and Flames.m4a
if (file.Contains(".m4a"))
{
stat_sorted_audio++;
var artist = file.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
bool exists = System.IO.Directory.Exists(#folder_music + artist[0] + "\\");
if (!exists)
{
System.IO.Directory.CreateDirectory(#folder_music + artist[0] + "\\");
}
string s_file = file.Replace("[" + artist[0] + "]", "");
string s_target = folder_music + artist[0] + "\\";
string s_source = folder_desktop + file;
label2.Text = s_file + "\n" + s_target + "\n" + s_source;
moveFile(s_source, s_target, s_file, ".m4a");
}
And the function to move files:
public void moveFile(string source, string target, string file)
{
if (!System.IO.File.Exists(target+file))
{
System.IO.File.Move(#source, #target + file);
}
}
This works fine and I end up with the files in the correct folder, but once the files have moved a padlock is appearing next to the icon, I don't want this.
Does anyone know why this is happening?

Error: "The process cannot access.... because it is being used by another process. " in Delete Image

I know others had a similar problem but my problem is specific for image...
I have an image function like below:
static public string Setimage(PictureBox pictureBox, OpenFileDialog ofd,string nameform,string folderform)
{
ofd.Title = "Select Pictures";
ofd.Filter = "Pictures(*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png | All file (*.*)| *.*";
ofd.DefaultExt = ".jpg"; // Default file extension
string namefile = "";
// Process open file dialog box results
if (ofd.ShowDialog() == DialogResult.OK)
{
// try
//{
string fileName = ofd.FileName;
if (ofd.SafeFileName.Length <= 50)
if (Image.FromFile(fileName).Width >= 640 && Image.FromFile(fileName).Height >= 480)
{
namefile = ofd.SafeFileName;
if (namefile != "Null_0_Null" || namefile != null)
{
string oldPath = #ofd.FileName;
string newFileName = namefile;
newpath = Application.StartupPath + #"\userpictures\" + #"Apartment\";
deladdress = newpath + folderform + #"\" + #newFileName;
Random rand = new Random();
string pp=newpath+folderform;
// string pdest;
#region Check Directory And File To copy
if (Directory.Exists(newpath + folderform))
{
if (!File.Exists(newpath + folderform + #"\" + #newFileName))
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
// else
// {
// File.Delete(newpath + folderform + #"\" + #newFileName);
// File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
//}
}
else
{
Directory.CreateDirectory(newpath + folderform);
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
}
#endregion
pictureBox.BackgroundImage = Image.FromFile(newpath + folderform + #"\" + #newFileName);
}
else { MessageBox.Show("filename" + namefile + "Not valid"); }
}
else { MessageBox.Show("Size of file not valid"); }
else { MessageBox.Show("size of name file not valid"); }
// }
// catch { MessageBox.Show("your file that you selected is not valid please select anyone."); }
}
return namefile;
}
For loading image I have this function:
static public void loadimage(PictureBox pictureBox, string img, string nameform, string folderform)
{
try
{
if (img != "Null_0_Null")
if (!System.IO.File.Exists(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img))
{
pictureBox.BackgroundImage = Image.FromFile(Application.StartupPath + "\\filepictures\\default4.PNG");
}
else
{
pictureBox.BackgroundImage =Image.FromFile(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img);
}
}
catch { }
}
In my form I call this functions. For set image I write a private string in my form:
string img1;
And for loading image in my form load write this:
loadimage(pictureBox1, "Blue hills.jpg","me", "Apartment");
img1 = "Blue hills.jpg";
For Setimage I have this:
img1=Setimage(pictureBox1, openFileDialog1,"me", "Apartment");
And when I use this code for delete image show me error "process can not be access ..."
System.IO.File.Delete("image path");
When you use Image.FromFile, that will open a file handle to that file and keep it open until the image is disposed.
You should:
Only call Image.FromFile once and reuse the object in Setimage (you're loading it twice in a single if condition...)
Dispose of every Image when you're done with it
Dispose of the old BackgroundImage before you set the new one
So long as you dispose of every Image which is related to the file before you delete the file, you should be okay.

System.UnauthorizedAccessException: Access to the path C

I am trying to build a automatic backup and restore system.
My logfile:
2012-08-02 22:34:06 - Init: Folder main created for server Teamdeathmatch
2012-08-02 22:34:06 - Backup: Couldn't copy files: System.UnauthorizedAccessException: Access to the path 'C:/temp/backups/Teamdeathmatch/server/main' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
at BackupRollback.Backup.getServerFiles() in C:\Users\jordi\Desktop\ConsoleApplication1 - kopie\Backup.cs:line 51
The target and the file exist.
I hope that anyone can help me. Also some feedback about my programming of c# since c-sharp is new for me.
Thank you
class Backup
{
public static void getServerFiles()
{
Log.Info("Get servers");
string[] fileEntries = Directory.GetDirectories("c:/Gameservers");
Log.Info("Servers found: " + fileEntries.Count());
string _directoryPath = #"C:\temp\backups";
// check folder exists
if (!Directory.Exists(_directoryPath))
{
Log.Data("Temp backup folder not found");
Directory.CreateDirectory(_directoryPath);
Log.Data("Temp backup folder created successfully");
}
else
{
Log.Data("Temp backup folder found");
}
// move files to directory
foreach (string fileName in fileEntries)
{
try
{
string servername = Path.GetFileNameWithoutExtension(fileName);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/server");
Log.Data("Folder server created for server " + servername);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/server/main");
Log.Data("Folder main created for server " + servername);
File.Copy("C:/temp/backups/" + servername + "/server/main", "C:/Gameservers/" + servername + "/server/main/server.cfg");
Log.Data("File server.cfg copied for server " + servername);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/b3 server/conf");
Log.Data("Folder conf [b3] created for server " + servername);
File.Copy("C:/temp/backups/" + servername + "/server/main", "C:/Gameservers/" + servername + "/b3 server/conf/b3.xml");
Log.Data("File b3.xml copied for server " + servername);
Directory.CreateDirectory("C:/temp/backups/" + servername + "/server/mods");
Log.Data("Folder mods created for server " + servername);
DirectoryCopy("C:/temp/backups/" + servername + "/server/", "C:/Gameservers/mods/" + servername + "/server/mods/");
Log.Data("Folder mods copied for server " + servername);
}
catch (Exception ex)
{
Log.Data("Couldn't copy files: " + ex.ToString());
}
}
}
private static void DirectoryCopy(string sourceDirName, string destDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath);
}
}
}
File.Copy(source, destination)
You have your parameters reversed. Try this instead.
File.Copy"C:/Gameservers/" + servername + "/server/main/server.cfg",
"C:/temp/backups/" + servername + "/server/main");
Log.Data("File server.cfg copied for server " + servername);

Categories