File delete problem - please help me i cant delete a file .. when i try to delete the i get this massage
c# File.Delete - File being used by another processc# File.Delete -
File being used by another process
protected void Button2_Click1(object sender, EventArgs e)
{
HttpFileCollection hfc = Request.Files;
string x = "";
string foldername = DateTime.Now.ToString().Trim().Replace(" ", "").Replace(":", "").Replace("/", "");
string foldername1 = foldername+"1";
Directory.CreateDirectory(Server.MapPath("~/IMAGEUPLOADCENTER/") + foldername);
Directory.CreateDirectory(Server.MapPath("~/IMAGEUPLOADCENTER/") + foldername1);
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string name =(DateTime.Now.ToString() + i + hpf.FileName).ToString().Trim().Replace(" ", "").Replace(":", "").Replace("/", "");
hpf.SaveAs(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
ResizeImageWidth(497, Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name, Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
System.Drawing.Image upImage = System.Drawing.Image.FromFile(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name); //System.Drawing.Image.FromStream(FU1.PostedFile.InputStream);
System.Drawing.Image logoImage = System.Drawing.Image.FromFile(Server.MapPath("~/pages002248Xc54/UploadImages/LOGOnew.png"));
using (Graphics g = Graphics.FromImage(upImage))
{
g.DrawImage(logoImage, new Point(upImage.Width - logoImage.Width - 10, 10));
upImage.Save(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
File.Delete(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
// Image1.ImageUrl = "~/UploadFiles/2" + "//" + fileName;
}
x = x + "</br><img src='http://hela.co.il/IMAGEUPLOADCENTER/" + foldername + "/" + name + "'/></br>";
}
}
TextArea1.InnerText = x;
FileUpload1.Visible = false;
Button2.Visible = false;
}
Your file is being locked by you and that is preventing you from deleting it. The Image.FromFile method locks the file used to create the object until the Image object is disposed of. So in this case, the image file will remain locked until you dispose of upImage.
Move your File.Delete to after you're done with the image and it will work. In the code below, I added using statements to each variable so that they will get disposed of (and unlock the file), and then I moved the delete statement outside of the using block (after the Image objects are disposed of).
using(System.Drawing.Image upImage = System.Drawing.Image.FromFile(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name))
using(System.Drawing.Image logoImage = System.Drawing.Image.FromFile(Server.MapPath("~/pages002248Xc54/UploadImages/LOGOnew.png")))
using (Graphics g = Graphics.FromImage(upImage))
{
g.DrawImage(logoImage, new Point(upImage.Width - logoImage.Width - 10, 10));
upImage.Save(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
}
File.Delete(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
Image.FromFile Method (String)
using statement (C#)
Related
I have written the following code in a Timer's Tick event to checking if the file modification time of an image has changed then copy that image and save it to another directory. Sometimes GetLastWrittenTime() doesn't change even though the file has already been overwritten.
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp"))
{
DateTime filetime=File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
if (!filetime.Equals(lastmMdifiedTime))
{
if (txtkapan.Text != "" && txtlot.Text != "")
{
if (reg.Read("AUTOPATH") == null || reg.Read("AUTOPATH").Equals(""))
{
Directory.CreateDirectory("D:\\" + txtkapan.Text + "\\" + txtlot.Text);
}
else
{
Directory.CreateDirectory(reg.Read("AUTOPATH")+"\\" + txtkapan.Text + "\\" + txtlot.Text);
}
string image_name;
if (txtlot.Text.Length <= 3 || txtparty.Text.Length <= 3 || txtkapan.Text.Length <= 3)
{
image_name = txtparty.Text.Substring(0, txtparty.Text.Length) + "_" + txtkapan.Text.Substring(0, txtkapan.Text.Length) + "_" + txtlot.Text.Substring(0, txtlot.Text.Length) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
else
{
image_name = txtparty.Text.Substring(0, 3) + "_" + txtkapan.Text.Substring(0, 3) + "_" + txtlot.Text.Substring(0, 3) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
img.Save(reg.Read("AUTOPATH") + "\\" + txtkapan.Text + "\\" + txtlot.Text + "\\" + image_name, ImageFormat.Jpeg);
lastmMdifiedTime = File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString());
}
}
else { }
}
}
Please tell me what is wrong in my code.
private void button4_Click(object sender, EventArgs e)
{
FileStream outputFileStream = new FileStream("log.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outputFileStream);
// writing block
string originalPathFile = #"C:\Users\user\Downloads\CaptchaCollection\Small\";
string duplicatePath = #"C:\Users\user\Downloads\CaptchaCollection\Small\Duplicates\";
string movedOriginal = #"C:\Users\user\Downloads\CaptchaCollection\Small\Sorted\";
var files = Directory.GetFiles(originalPathFile)
.Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension))
.Where(name => { int number; return int.TryParse(name, out number); })
.Select(name => int.Parse(name))
.OrderBy(number => number).ToArray();
while (files.Length > 1)
{
string duplicateOfFolder = Directory.CreateDirectory(duplicatePath + files[0].ToString()).FullName;
for (int j = 1; j < files.Length; j++)
{
Bitmap im1 = new Bitmap(originalPathFile + files[0].ToString() + ".png");
Bitmap im2 = new Bitmap(originalPathFile + files[j].ToString() + ".png");
if (compare(im1, im2))
{
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png \n");
}
}
File.Move(originalPathFile + files[0].ToString() + ".png", movedOriginal + files[0].ToString() + ".png");
writer.WriteLine(files[0].ToString() + ".png " + "has had its duplicates removed.");
files = Directory.GetFiles(originalPathFile)
.Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension))
.Where(name => { int number; return int.TryParse(name, out number); })
.Select(name => int.Parse(name))
.OrderBy(number => number).ToArray();
}
writer.Close();
outputFileStream.Close();
}
So this button basically moves duplicate files of an image visually. I got this code from one of my previous questions I've asked. Now I want to use a new folder to place duplicates of a specific image.
For example:
1.png has 5 visual duplicates (65.png,87.png,100.png,103.png,156.png). I want to move all the duplicates to this directory instead of just placing it in the Duplicates directory: C:\Users\user\Downloads\CaptchaCollection\Small\Duplicates\1\
Now instead what's happening is that it apparently is renaming and regenerating some images. I can't really describe this in words because I can't really see what's going on. What's not happening is that those files are not being moved to the directory of a duplicated file organization.
Folders will create but instead it's not placing it in the proper folder.
If I understood your requirement correctly then I think issue is in following lines.
if (compare(im1, im2))
{
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png \n");
}
You are actually comparing first file with others but still copying the files in duplicate folder.
Replace following line
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
with
String path = duplicateOfFolder;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.Move(originalPathFile + files[j].ToString() + ".png", path + "\\" + files[j].ToString() + ".png");
This should work.
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.
I am trying to create a hash text file. The code works, the problem is that once the streamwriter starts the process it won't stop until it is finished. I want to break up the output file into smaller parts. How do I stop the streamwriter and start a new file without starting the process over again?
string infile = #"ntlmchar.txt";
string hashfile = #"ntlmhash.txt"; //File that includes the hash and clear test
string charfile = #"ntlmchar.txt"; //File that only has the clear text
string oldCharFile = ""; //Temp file to apply to infile.
int cint = 1; //The number of characters in the file
string str_cint = cint.ToString(); //convert cint to string
int pint = 1; //The number of parts to the character file
string str_pint = pint.ToString(); //convert pint to string
int cm = 4; //Max number of characters
int pm = 4000; //Man number of parts
int line = 0; //line index number
while (cint <= cm)
{
if (!File.Exists(infile))
{
for (int ci =1; ci <= cm; ci++)
{
str_cint = cint.ToString();
for (int pi =1; pi <= pm; pi++)
{
str_pint = pint.ToString();
// System.Console.WriteLine("Inner for loop cint file does not exist" +cint +" pint " + pint);
// System.Console.WriteLine("Inner for loop str_cint file does not exist " + str_cint + " cint " + cint);
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
pint = pi;
oldCharFile = charfile;
infile = oldCharFile;
if (File.Exists(infile)) break;
// System.Console.WriteLine("inner loop file " + infile);
}
// System.Console.WriteLine("outer for loop cint " + cint + " pint " + pint);
// System.Console.WriteLine("infile not found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
// System.Console.WriteLine("No work files found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
else if (File.Exists(infile))
{
// Create a file to write to.
// System.Console.WriteLine("cint at the start of else if " + cint + " str_cint " + str_cint);
infile = oldCharFile;
str_cint = cint.ToString();
// System.Console.WriteLine("cint after assign to str_cint " + cint + " str_cint " + str_cint);
pint=1;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
//System.Console.WriteLine(infile + " " + oldCharFile + " " + charfile + " " + hashfile);
// System.Console.WriteLine("Infile found " + cint + " " + pint);
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
foreach (string s in alpha)
{
if (line <= 2000000)
{
string j = i + s;
string str = Program.Ntlm(j);
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
// System.Console.WriteLine("line before writing to file " + line + " in charfile " + charfile);
h.WriteLine("{0}, {1}", j, str);
c.WriteLine("{0}", j);
line++;
// System.Console.WriteLine("h file" + h + " c file" + c);
}
else
{
h.Flush();
c.Flush();
pint++;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
line = 1;
System.Console.WriteLine("line after writing to part of file " + line + " in charfile " + charfile);
}
}
}
I assume you're trying to get 2,000,000 items per file? You just need to restructure a little.
Right now you have:
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
You need to change your code so that you open the output files later:
using (StreamReader sr = new StreamReader(infile))
{
StreamWriter h = null;
StreamWriter c = null;
try
{
h = new StreamWriter(...);
c = new StreamWriter(...);
string i = "";
while ((i = sr.ReadLine()) != null)
{
// output line here
// and increment line counter.
++line;
if (line > 2000000)
{
// Close the output files and open new ones
h.Close();
c.Close();
h = new StreamWriter(...);
c = new StreamWriter(...);
line = 1;
}
}
}
finally
{
if (h != null) h.Close();
if (c != null) c.Close();
}
}
I am using an image control, but it does not display any image. When I see its viewsource, it displays the image path correct. The URL of the page is devweb.tsgdomain.com/americaneyenew/News.aspx
lblTitle.Text = dtNews.Rows[0]["NewsTitle"].ToString();
string strPhotosImage = dtNews.Rows[0]["Image"].ToString();
if (strPhotosImage != string.Empty)
{
string Extension = strPhotosImage.Substring(strPhotosImage.LastIndexOf("."));
// Server.MapPath("~/ENewsLetterFileUpload/NPH_" + strOriginalFileName + "_1.PDF");
ImgNews.ImageUrl = Server.MapPath("~/ENewsImage/" + iNewsID + "_1" + Extension);
//Server.MapPath("~/ENewsImage/" + iNewsID + "_1" + Extension);
//"../ENewsImage/" + iNewsID + "_1" + Extension;
ImgNews.Visible = true;
}
else
{
ImgNews.Visible = false;
}
Please help me as soon as possible.
you shouldn't use as server.mappath
ImgNews.ImageUrl = "~/ENewsImage/" + iNewsID + "_1" + Extension;
would be enough.
I think you have the wrong URL.
When you do :
String testURL = Server.MapPath("~/ENewsImage/" + iNewsID + "_1" + Extension);
Response.Redirect(testURL);
Is your image there?
Make sure the URL is correct by printing it to the screen or visiting it.