Check for duplicates files on upload in c# - c#

With this asp net page upload file in C# I need check for duplicates files.
I accept 3 files in upload on the server.
This code worked and the duplicates file are not uploaded, but the alert popup is open only for the first duplicate file send to upload even when duplicates are more.
What's the problem ?
My code below, thank you in advance.
if (File.Exists(upload.FileName))
{
DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("\\images\\"));
FileInfo[] objFI = objDir.GetFiles("*.*");
int iFileCnt = 0;
if (objFI.Length > 0)
{
foreach (FileInfo file in objFI)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('This file exists " + upload.FileName + "');", true);
iFileCnt += 1;
}
}
}

Change "Msg" to the the "Msg" + iFileCnt. This changes the key for every iteration.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg" + iFileCnt, "alert('This file exists " + file.Name + "');", true);
Now alert execute more then once in loop.

How about something like this?
List<string> Filenames = new List<string>()
{
"File1.jpg",
"File2.jpg"
//etc.
};
foreach(string s in Filenames)
{
Upload(s);
}
private void Upload(string filename)
{
string directory = #"\\path\\to\\directory";
string fullpath = string.Format(#"{0}\{1}", directory, filename);
if(File.Exists(fullpath))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('This file exists " + filename + "');", true);
}
}

Related

How to add local file link to Exported CSV file using C#

I want to add the link to my local file into one of the columns of Exported CSV file.So that when user clicks on the link the local file open. I have searched the internet for this but can't find any good solution.
Here is the screenshot of what i try to do -
Suppose when user clicks on File path selected row file full name then upon click i should open the file at that localtion.
My code to generate the CSV file is-
public void GetExportDetailsCSV(ExportInformation ExportInfo)
{
StringBuilder cameraRows = new StringBuilder();
string filePath = ExportInfo.ExportOutputPathAtClient + SLASH_STRING + "ExportDetails.csv";
string columnsNames = "File Name ,File Path" + "\r\n";
if(Directory.Exists(ExportInfo.ExportOutputPathAtClient))
{
try
{
foreach (string newPath in Directory.GetFiles(string.Format("{0}{1}", ExportInfo.ExportOutputPathAtClient, SLASH_STRING), "*" + ExportInfo.VideoFileFormat.ToString(), SearchOption.AllDirectories))
{
FileInfo FileDetails = new FileInfo(newPath);
cameraRows.Append(string.Format("{0},{1}\r\n", FileDetails.Name, FileDetails.FullName));
}
string FinalData = "\nExport Remarks : Simple Export " + "\n\n" + "," + "," + "," + "," + "File Details" + "," + "\r\n" + "\r\n" + columnsNames + "\n " + cameraRows;
using (var stream = System.IO.File.CreateText(filePath))
{
stream.WriteLine(FinalData);
}
}
catch(Exception ex)
{
}
}
}
My question is simple how can i put file location value as a link in my Exported CSV file.
Thankyou!
Try using the Hyperlink function. Check this link
You can try this sample. Open notepad type below the line and save it as CSV.
This,is,demo,"=HYPERLINK(""http://www.google.com/"",""Link"")"
Hopefully, this will solve the problem.

C# While loop not working

New programmer working on a little file mover. Not sure why my while statement is not working. I am trying to have the program check if the file exists in the directory and if so, counter++ until it comes up with an original name e.g. 2018 Picture(45) and so on...
private void btnMove_Click(object sender, EventArgs e)
{
string sourcePath = #"C:\Users\David\Desktop\Personal Pictures & Videos\fromme";
string destinationPath = #"C:\Users\David\Desktop\Personal Pictures & Videos\practicefolder";
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
string[] sourcefiles = Directory.GetFiles(sourcePath);
//looks at each file with its path attached.
int counter = 1;
foreach (string sourcefile in sourcefiles)
{
if (sourcefile.EndsWith(".jpeg"))
{
string destFile = Path.Combine(destinationPath, "2018 Picture" + "(" + counter + ")" + ".jpeg");
MessageBox.Show(destFile);
while (Directory.Exists(destFile))
{
counter++;
}
//renames and moves files from sourcePath to destinationPath
File.Move(sourcefile, destFile);
Incrementing just the counter does not automatically update the file name, which you check to exist for the break condition of the loop.
while(File.Exists(destFile))
{
counter++;
destFile = Path.Combine(destinationPath, $"2018 Picture({ counter }).jpeg");
}
We have to update the file name with the incremented counter every time.
The $ syntax for string concatenation is optional but makes the file name composition clearer.
Furthermore, Directory.Exists does not work for files. If you pass a file name that exists, it will still return false, because it checks for the directory flag on the file system entry.
Put the your code creating the filename inside the loop and the File.Move outside of the loop. You should also set an upper limit on "counter" so that you can't get stuck in an infinite loop. Then only do the File.Move if you don't hit the limit. Since you're going to be changing the name with every iteration, you should only display the messagebox after the new filename has been successfully found.
foreach (string sourcefile in sourcefiles)
{
if (sourcefile.EndsWith(".jpeg"))
{
bool bSuccess = true;
string destFile = Path.Combine(destinationPath, "2018 Picture" + "(" + counter + ")" + ".jpeg");
counter = 0;
while (File.Exists(destFile))
{
destFile = Path.Combine(destinationPath, "2018 Picture" + "(" + counter + ")" + ".jpeg");
counter++;
if(counter>1000)
{
MessageBox.Show("'Too many tries.' or what ever message you want to use.");
bSuccess = false;;
}
}
if(bSuccess)
{
MessageBox.Show(destFile);
File.Move(sourcefile, destFile);
}
}
I found several things to correct or improve.
private void btnMove_Click(object sender, EventArgs e)
{
string sourcePath = #"C:\Users\David\Desktop\Personal Pictures & Videos\fromme";
string destinationPath = #"C:\Users\David\Desktop\Personal Pictures & Videos\practicefolder";
//no need to check if the path exists. CreateDirectory() already does the right thing
Directory.CreateDirectory(destinationPath);
int counter = 0;
var sourcefiles = Directory.EnumerateFiles(sourcePath, "*.jpeg");
foreach (string sourcefile in sourcefiles)
{
bool tryAgain = true;
while (tryAgain)
{
try
{
counter++;
destFile = Path.Combine(destinationPath, $"2018 Picture ({ counter }).jpeg");
File.Move(sourcefile, destFile);
tryAgain = false;
MessageBox.Show(destfile);
}
catch(IOException ex)
{ //file I/O is one of the few places where exceptions might be okay for flow control
tryAgain = (counter < 10000);
}
}
}
}

Incorrect output for check existing file in upload in c#

With this asp net page upload file in C# I need to check for duplicates.
I accept 3 files in upload on the server.
After uploading the new 3 files on the server, I have tried to upload the same file 3 files now existing on the server.
For 3 files jpg existing on the server the response code on the Label is incorrect because is :
File exist IMG0006A.jpg
And not
File exist IMG0002A.jpg, IMG0005A.jpg, IMG0006A.jpg
What's the problem ?
Why if I have in the code foreach in Label the output is only for last existing file ?
My code below, thank you in advance for any help.
if (File.Exists(theFileName))
{
objDir = new DirectoryInfo(Server.MapPath("\\images\\));
objFI = objDir.GetFiles("*.*");
iFileCnt = 0;
if (objFI.Length > 0)
{
foreach (FileInfo file in objFI)
{
if (file.Name.ToString() == Path.GetFileName(theFileName))
{
lblFileList.Text = "File exist " + Path.GetFileName(theFileName);
iFileCnt += 1;
}
}
}
}
In addition to Jonathan's answer. He is checking for just one file name i.e. theFileName. You should loop through all your three files:
Assuming that fileNames is the list of your three file names.
int iFileCount = 0;
foreach (string fileName in fileNames)
{
if (!System.IO.File.Exists(fileName)) continue;
if(iFileCount <= 0)
{
lblFileList.Text = "File exist " + System.IO.Path.GetFileName(fileName);
}
else
{
lblFileList.Text += ", " + System.IO.Path.GetFileName(fileName);
}
++iFileCount;
}
Try
if (File.Exists(theFileName))
{
objDir = new DirectoryInfo(Server.MapPath("\\images\\));
objFI = objDir.GetFiles("*.*");
if (objFI.Length > 0)
{
foreach (FileInfo file in objFI)
{
if (file.Name.ToString() == Path.GetFileName(theFileName))
{
if (iFileCnt == 0)
{
lblFileList.Text = "File exist " + Path.GetFileName(theFileName);
}
else
{
lblFileList.Text += ", " + Path.GetFileName(theFileName);
}
iFileCnt += 1;
}
}
}
}
Note that iFileCnt = 0 needs to be set earlier, otherwise for every new file it is 0.
If I understand what you are doing correctly, however, it would be better to get your list of existing files earlier, rather than refreshing it each time. All you need to do, is add each successful file to the FileInfo array, to ensure that the list is complete.

Why won't my code upload a file to the specified folder on the web server when using the fileupload control?

Good afternoon. I have an asp.net web forms application using c#. I am having some difficulty getting my code to work properly. The data is uploaded successfully to the sql server database, but the file isn't saved to the specified "Data" folder. any help would be greatly appreciated?
The ID of the fileupload control is "fu_doc_upld". I don't get any errors when using the form, the files just aren't saving to the "Data" folder (or any other folder). Here is the code behind that I'm using:
protected void btn_frm_new_doc_save_close_Click(object sender, EventArgs e)
{
int i = 0;
string filename = fu_doc_upld.FileName;
if (fu_doc_upld.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";
fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
}
hdn_filename_txt.Value = (Server.MapPath("~/Data/") + filename);
hdn_doc_uplod_dt_txt.Value = DateTime.Now.ToString();
SqlConnection idrf_cnxn = new SqlConnection("Data Source=WDBSVCPRD01\\SVCDB;Initial Catalog=idrf;Integrated Security=True");
{
SqlCommand new_doc_cmd = new SqlCommand("Insert Into tbl_doc(doc_title, doc_type_list, doc_org_list, doc_dept_list, doc_desc, prior_contract_cd, legal_comp_contract_id, doc_upld_dt, doc_path, vendor_id_fk) Values(LTRIM(RTRIM(#doc_title)), LTRIM(RTRIM(#doc_type_list)), LTRIM(RTRIM(#doc_org_list)), LTRIM(RTRIM(#doc_dept_list)), LTRIM(RTRIM(#doc_desc)), LTRIM(RTRIM(#prior_contract_cd)), LTRIM(RTRIM(#legal_comp_contract_id)), LTRIM(RTRIM(#doc_upld_dt)), LTRIM(RTRIM(#doc_path)), LTRIM(RTRIM(#vendor_id_fk)))", idrf_cnxn);
new_doc_cmd.Parameters.AddWithValue("#doc_title", doc_title_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_type_list", doc_type_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_org_list", doc_org_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_dept_list", doc_dept_ddl.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_desc", doc_desc_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#prior_contract_cd", prior_contract_cd_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#legal_comp_contract_id", lgl_comp_cont_id_txt.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_upld_dt", hdn_doc_uplod_dt_txt.Value);
new_doc_cmd.Parameters.AddWithValue("#doc_path", hdn_filename_txt.Value);
new_doc_cmd.Parameters.AddWithValue("#vendor_id_fk", hdn_vendor_id_txt.Value);
idrf_cnxn.Open();
new_doc_cmd.ExecuteNonQuery();
idrf_cnxn.Close();
if (IsPostBack)
{
Response.Redirect("~/Default.aspx");
}
}
}
Any help would be greatly appreciated.
Thanks,
J
You only call SaveAs() when the file exists. You could've found this by placing a breakpoint and stepping through your code.
Move the save out of the loop:
string filename = fu_doc_upld.FileName;
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_doc_upld.FileName + " (" + i.ToString() + ")";
}
fu_doc_upld.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
Note that this code will remove the extension if a file already exists. See C#: How would you make a unique filename by adding a number? for a better implementation.

will only copy first item in the array c#

Hi I am trying to write a simple program to copy a folder from one soure to many in parallel.
I am learning c# so have been trying to understand and change code examples, as i figured this the best way to learn somthing new.
The example below does not work as it only copies to the first destination in the destinationPaths
The stange thing is i have a simlar method to copy one file to many and this works everytime
have i missing something?? i would be greatful if someone could tell me why this is not working i am guessing that there maybe certain things you can't do in parallel
any advice would be great
public void CopyMultipleFolder(string sourceFilePath, params string[] destinationPaths)
{
if (string.IsNullOrEmpty(sourceFilePath)) MessageBox.Show("A source file must be specified.", "sourceFilePath");
else
{
if (destinationPaths == null || destinationPaths.Length == 0) MessageBox.Show("At least one destination file must be specified.", "destinationPaths");
else
{
try
{
FileIOPermission writeAccess = new FileIOPermission(FileIOPermissionAccess.AllAccess, destinationPaths);
foreach (string i in destinationPaths)
{
writeAccess.AddPathList(FileIOPermissionAccess.Write, i);
}
writeAccess.Demand();
NetworkCredential user = new NetworkCredential();
user.UserName = Properties.Settings.Default.username;
user.Password = Properties.Settings.Default.password;
if (user.Password.Length == 0 || user.UserName.Length == 0)
{
MessageBox.Show("No Username or password have been entered click username on menu bar to update", "Update Credentials");
}
else
{
Parallel.ForEach(destinationPaths, new ParallelOptions(),
destinationPath =>
{
if (sourceFilePath.EndsWith("*"))
{
int l = sourceFilePath.Length - 4;
sourceFilePath = sourceFilePath.Remove(l);
}
else
{
using (new NetworkConnection(destinationPath, user))
{
if (Directory.Exists(destinationPath + "\\" + foldername))
{
if (destinationPath.EndsWith("\\"))
{
DialogResult r = MessageBox.Show("Folder already Exists " + destinationPath + foldername + " Do You Want To overwrite All Files And Sub Folders", "Overwrite?", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
PleaseWait.Create();
foreach (string dirPath in Directory.GetDirectories(sourceFilePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourceFilePath, destinationPath + "\\" + foldername));
foreach (string newPath in Directory.GetFiles(sourceFilePath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceFilePath, destinationPath+ "\\" + foldername), true);
list = list + destinationPath + foldername + Environment.NewLine;
}
else
{
}
}
else
{
DialogResult r = MessageBox.Show("Folder already Exists " + destinationPath + "\\" + foldername + " Do you Want to overwrite All Files And SubFolders", "Overwrite?", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
PleaseWait.Create();
foreach (string dirPath in Directory.GetDirectories(sourceFilePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourceFilePath, destinationPath + "\\" + foldername));
//Copy all the files
foreach (string newPath in Directory.GetFiles(sourceFilePath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceFilePath, destinationPath + "\\" + foldername), true);
list = list + destinationPath + "\\" + foldername + Environment.NewLine;
}
else
{
}
}
}
else
{
PleaseWait.Create();
foreach (string dirPath in Directory.GetDirectories(sourceFilePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourceFilePath, destinationPath + "\\" + foldername));
//Copy all the files
foreach (string newPath in Directory.GetFiles(sourceFilePath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceFilePath, destinationPath + "\\" + foldername), true);
list = list + destinationPath +"\\"+foldername+ Environment.NewLine;
}
}
}
PleaseWait.Destroy();
});
MessageBox.Show("Folder Has Been Copied to " + list, "Folder Copied");
}
}
catch (UnauthorizedAccessException uae)
{
MessageBox.Show(uae.ToString());
}
}
}
}
You wrote you were learning C#. So, forget about parallel execution, because it unnecessarily makes your task more complicated. Instead, start by decomposing your problem into smaller parts. The code you posted is ugly, long, repeats a lot of logic many times, and hence it is and will be hard to read, debug, and maintain.
So, start by writing small functions for individual files. You need to create a set of folders in a destination folder. Hence write a function accepting a list of names and the destination folder. You need to determine the set of folders from a source folder. So write a function which does that. The combine those two functions together. And so on.
You will end up with a much cleaner, modifiable, reusable solution. Then it will be a lot easier to plug in parallel processing. Most likely, this will be for the sake of learning it, because it makes not much sense to parallelize your problem too heavily.

Categories

Resources