I am trying to increment the filename (e.g., "file1.csv", "file2.csv", etc.), each time a new file is generated. I followed this thread Increment the file name if the file already exists in c# but the solution is not useful for my case. What I want to do is check if the file exists in the first place and if it does write in it. If it doesn't create one and write. The problem is that if the file exists but it's from another user, I want the system to increment the file number and not write to the same file just because it exists. What I have so far:
public void saveFile()
{
int count = 0;
string title = "TimeStamp,Name,Trial,Time_spent-dist,Time_spent_tar\n";
string output = System.DateTime.Now.ToString("mm_ss_ffff") + "," +
currentScene.name.ToString() + "," +
trialNum.ToString() + "," +
timerDistractor.ToString() + "," +
timerTarget.ToString();
string fname = "User_" + count + ".csv";
string path = Path.Combine(Application.persistentDataPath, fname);
if (File.Exists(path))
{
File.AppendAllText(path, "\n" + output);
}
else
{
StreamWriter writer = new StreamWriter(path);
writer.WriteLine(title + "\n" + output);
writer.Close();
}
}
Any pointers?
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.
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#)
I'm writing a application that reads Ia directory contents and writes that to a csv file. I'm trying to get a list of certain file extensions from and upload path which contains a csv file and write a list of the filtered extensions to a new csv file.
I cant figure out how to get the filtered csv file written.....
Here's my method.
StringBuilder CreateUserFileUploadList(SLDocument document, StringBuilder destroyWorksheet)
{
document.SelectWorksheet("User Folder");
var stats = document.GetWorksheetStatistics();
var rowcount = stats.EndRowIndex + 1;
List unwantedExtensions = cblExtensions.Items.Cast().Where(li => li.Selected).Select(li => li.Text).ToList();
if (!String.IsNullOrEmpty(tbOtherExtensions.Text))
{
unwantedExtensions.AddRange(tbOtherExtensions.Text.ToUpper().Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
}
unwantedExtensions.AddRange("EXE,COM,BAT,JS,VBS,PIF,CMD,DLL,OCX,PWL".Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
// new CSV file
var workSheet = new StringBuilder();
workSheet.AppendLine("FILEPATH,Client,Matter,LAST MODIFIED DATE,CREATED DATE,CREATED BY,LAST MODIFIED BY,FOLDER,DOCUMENT NAME,Author,Practice Area,Document Type,ACCESS,Keywords - Comments");
// loop through the directories
for (int i = 2; i 100 chars, or including TAB / \ : * ? " |
// Folder has folders>500 or has files>1000
//TODO: this loops through leaf folders; we need to check intermediate folders to ensure they don't have too many files or folders or a bad name
//Took out #"\",
bool invalidFolderName = new string[] { "/", ":", "*", "?", "" }.Any(s => directoryName.Contains(s));
if (invalidFolderName || directoryName.Length > 200 || files.Count() > 1000)
{
System.Diagnostics.Debug.WriteLine("INVALID folder: " + directoryName);
lblError.Text = lblError.Text + "\r\n" + "INVALID folder: " + directoryName;
//TODO: This should cause the WHOLE upload to fail
}
// build the target folder path
string folder;
string[] stringSeparators = new string[] { tbAuthor.Text };
var path = directoryName.Split(stringSeparators, StringSplitOptions.None);
folder = path.Last();
if (path.Count() > 1)
{
folder = ConfigurationManager.AppSettings["NetDocumentsFolderPath"].ToString() + tbAuthor.Text + #"\User Folder" + folder;
if (folder.Substring(folder.Length - 1, 1) == #"\")
{
folder = folder.Substring(0, folder.Length - 1);
}
}
// Get the files
foreach (var file in files)
{
// Remove unwanted extensions
if (!unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{
var access = file.GetAccessControl();
string user = access.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
//TODO: FWIW, fileName (on netdocs) does NOT need to match the name in the original location...
string fullName = file.FullName;
string fileName = file.Name;
// Wrap in quotes if there are any invalid characters
if (fullName.IndexOfAny(csvTokens) >= 0)
{
fullName = "\"" + fullName.Replace("\"", "\"\"") + "\"";
}
if (fileName.IndexOfAny(csvTokens) >= 0)
{
fileName = "\"" + fileName.Replace("\"", "\"\"") + "\"";
}
if (!document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{
String practiceArea = GetPracticeAreaForClientMatter(document.GetCellValueAsString(i, 2), document.GetCellValueAsString(i, 3));
String documentType = ConfigurationManager.AppSettings["FileDocumentType"].ToString();
// Validate file
// Invalid file names (>200 chars, or TAB / \ : * ? " |
// Invalid file size (>200 MB)
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
//TODO: This should cause the WHOLE upload to fail
}
else
{
workSheet.AppendLine(
fullName + "," +
document.GetCellValueAsString(i, 2) + "," +
document.GetCellValueAsString(i, 3) + "," +
file.LastWriteTime + "," +
file.CreationTime + "," +
tbAuthor.Text + "," +
tbAuthor.Text + "," +
folder + "," +
fileName + "," +
tbAuthor.Text + "," +
practiceArea + "," +
documentType + "," +
practiceArea + "|V," +
"Imported from Departed Attorney on: " + DateTime.Now.ToString("G"));
}
}
else
{
destroyWorksheet.AppendLine(fullName);
}
}
}
}
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{// Files in folders marked "destroy" are saved elsewhere
//destroyWorkSheet.Append(string.Format("{0}", "Directory" + fullName));
//destroyWorkSheet.Append(string.Format("{1}", "FileName" + fullName));
// destroyWorkSheet.AppendLine("Directory, FileName");
// destroyWorkSheet.Append(string.Format("{0},{1}", "Directory", "FileName") + fullName);
destroyWorksheet.AppendLine(fullName);
}
// Validate file for name (less than 200 chars, can't have TAB / \ : * ? " | ) and size ( less than 200 MB)
else if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{// This should cause the WHOLE upload to fail
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
errorWorksheet.AppendLine("INVALID file: " + file.Name);
}
else if (unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{// Files with unwanted extensions are filtered out
filterWorksheet.AppendLine(fullName);
}
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.