How to search image which image name contain '12345' in textbox - c#

I'm a newbie in C# programming language. I need some guide on how can I search image in textbox which just typing image name that contain 12345. This is because each image name in my folder is naming like this > JUN (12345). I want the image display at picturebox after typing 12345 in textbox. Here is my code that I already try it not display image that contain 12345. Hope anyone can help me. Thanks
private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxWorkNo.Text != "")
{
//Do something
string selectSql = "select name, empno, icnum, passport, deptno, section, designation from m_employee where workno=#workno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#workno", textBoxWorkNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxEmplNo.Text = (read["empno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
textBoxDesignation.Text = (read["designation"].ToString());
//BaseFolder that contains the multiple folders
//If the folders don't share the same base folder make an array with full paths
string baseFolder = "C:\\Users\\hamizah\\Desktop\\photo";
string[] employeeFolders = Directory.GetDirectories(baseFolder);
//Search image
string imgName = "%'" + textBoxEmplNo.Text + "%'" + ".jpg";
//Bool to see if file is found after checking all
bool fileFound = false;
foreach (var folderName in employeeFolders)
{
var path = Path.Combine(folderName, imgName);
if (File.Exists(path))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(path);
fileFound = true;
//If you want to stop looking, break; here
}
}
if (!fileFound)
{
//Display message that No such image found
pictureBox1.Visible = true;
pictureBox1.Image =
Image.FromFile(#"C:\Users\hamizah\Desktop\images\photo\No-image-found.jpg");
}
dataGridView1.Visible = false;
}
}
if (!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxEmplNo.Text = "";
textBoxName.Text = "";
}
}
}

File.Exists looks for one specific file. There is no file with weird name %'12345%'.jpg I guess. You can use this form:
foreach (var f in Directory.EnumerateFiles(rootPath, "*12345*.jpg")){
...
}

If it's already on the disk just use Directory.GetFiles() like so:
var strings = Directory.GetFiles(".","*12345*");
foreach (var s in strings)
{
Debug.Write(s);
}

You can use below code to get the files in the specific directory, which has a partial matching names as input value.
For each directory you are iterating through get the directory info first:
DirectoryInfo directoryInfo = new DirectoryInfo(#"c:\");
Then get the files as mentioned below:
FileInfo[] fileInfoArray = directoryInfo.GetFiles("*" + inputFileName + "*.*");
Then you can check the fileInfoArray for the file you are looking for. It can return multiple file info, depending on your input.
For reference: added the actual code here:
string partialInputName = "12345"; //textbox input value or whatever you want to input
string[] directories = Directory.GetDirectories(#"C:\Code");
FileInfo fileinDir;
foreach(string dir in directories)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (dirInfo.Exists)
{
//taking the first (FirstOrDefault()), considering that all files have a unique name with respect to the input value that you are giving. so it should fetch only one file every time you query
fileinDir = dirInfo.GetFiles("*" + partialInputName + "*.*").FirstOrDefault();
}
}

Related

How to create the zip file from the selected rows of datagridview in c#

I am displaying certain elements from .xml files into a DataGridView and it's working fine.
Here is the code to select the xml files
//Browse Folder
private void Btn_SelectFolder_Click(object sender, EventArgs e)
{
try
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK)
{
DataTable dt = new DataTable();
dt.Rows.Clear();
dt.Columns.Add("Select", typeof(bool));
dt.Columns.Add("File_Name");
dt.Columns.Add("Vendor_Name");
dt.Columns.Add("Vendor_ID");
dt.Columns.Add("Date_Range", typeof(DateTime));
lbl_Path.Text = fbd.SelectedPath;
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.xml");
XmlDocument doc = new XmlDocument();
XmlNodeList nodes = doc.GetElementsByTagName("cfdi:Emisor");
XmlNodeList nodes1 = doc.GetElementsByTagName("cfdi:Comprobante");
foreach (string tot_file in files)
{
doc.Load(tot_file);
string FileName = Path.GetFileNameWithoutExtension(tot_file);
for (int i = 0; i < nodes.Count; i++)
{
string Name = nodes[i].Attributes["Nombre"].Value;
string ID = nodes[i].Attributes["Rfc"].Value;
string Date = nodes1[i].Attributes["Fecha"].Value;
DataRow row = dt.NewRow();
row["File_Name"] = FileName;
row["Vendor_Name"] = Name;
row["Vendor_ID"] = ID;
row["Date_Range"] = Date;
dt.Rows.Add(row);
}
}
XML_Grid.DataSource = dt;
txt_FileName.ReadOnly = false;
txt_Name.ReadOnly = false;
txt_ID.ReadOnly = false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now what i want is to select the rows from DataGridView and create the zip file of selected files.
I have tried this code to create the zip file:
//Create Zip
private void Btn_SaveZip_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string folderToZip = lbl_Path.Text;
string zipFile = saveFileDialog1.FileName + ".zip";
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
DirectoryInfo di = new DirectoryInfo(folderToZip);
FileInfo[] filesToArchive = di.GetFiles();
if (filesToArchive != null && filesToArchive.Length > 0)
{
foreach (FileInfo fileToArchive in filesToArchive)
{
zipArchive.CreateEntryFromFile(fileToArchive.FullName, fileToArchive.Name, CompressionLevel.Optimal);
}
}
}
MessageBox.Show("Zip File Successfully Created", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
}
The above code is working fine and creating zip file But it's directly checking the files from the path and creating zip file of that folder.
How to select the files from DataGridview not directly from the folder and create the zip file of selected files.
My Form:
Any help would be helpful for me, I've been trying to get this working for hours now.
If I understood your problem correctly, you want to save only those files where the Select column is checked in your data grid into one zip file.
If so, the following modification to your Zip save routine can help you with that:
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
List<FileInfo> filesToArchive = new List<FileInfo>();
DirectoryInfo di = new DirectoryInfo(folderToZip);
// loop through all of the rows in the data grid
foreach (DataGridViewRow row in XML_Grid.Rows)
{
DataRowView rowView = row.DataBoundItem as DataRowView;
if (rowView == null) continue; // new row or not bound, ignore
var selectedValue = rowView["Select"]; // get the value for the select column
if (selectedValue == DBNull.Value || selectedValue == null || !(bool)selectedValue) // ignore null or false
continue;
string fileName = rowView["File_Name"].ToString(); // get the file name
var files = di.GetFiles(fileName + ".*"); // we had no extension so search the folder to get the full path
filesToArchive.AddRange(files); // add those file(s) to the list to archive
}
if (filesToArchive != null && filesToArchive.Count > 0)
{
foreach (FileInfo fileToArchive in filesToArchive)
{
zipArchive.CreateEntryFromFile(fileToArchive.FullName, fileToArchive.Name, CompressionLevel.Optimal);
}
}
}

How can I get values from a csv file where some of the cells contain commas?

I have a script that imports a csv file and reads each line to update the corresponding item in Sitecore. It works for many of the products but the problem is for some products where certain cells in the row have commas in them (such as the product description).
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (UpdateFile.PostedFile != null)
{
var file = UpdateFile.PostedFile;
// check if valid csv file
message.InnerText = "Updating...";
Sitecore.Context.SetActiveSite("backedbybayer");
_database = Database.GetDatabase("master");
SitecoreContext context = new SitecoreContext(_database);
Item homeNode = context.GetHomeItem<Item>();
var productsItems =
homeNode.Axes.GetDescendants()
.Where(
child =>
child.TemplateID == new ID(TemplateFactory.FindTemplateId<IProductDetailPageItem>()));
try
{
using (StreamReader sr = new StreamReader(file.InputStream))
{
var firstLine = true;
string currentLine;
var productIdIndex = 0;
var industryIdIndex = 0;
var categoryIdIndex = 0;
var pestIdIndex = 0;
var titleIndex = 0;
string title;
string productId;
string categoryIds;
string industryIds;
while ((currentLine = sr.ReadLine()) != null)
{
var data = currentLine.Split(',').ToList();
if (firstLine)
{
// find index of the important columns
productIdIndex = data.IndexOf("ProductId");
industryIdIndex = data.IndexOf("PrimaryIndustryId");
categoryIdIndex = data.IndexOf("PrimaryCategoryId");
titleIndex = data.IndexOf("Title");
firstLine = false;
continue;
}
title = data[titleIndex];
productId = data[productIdIndex];
categoryIds = data[categoryIdIndex];
industryIds = data[industryIdIndex];
var products = productsItems.Where(x => x.DisplayName == title);
foreach (var product in products)
{
product.Editing.BeginEdit();
try
{
product.Fields["Product Id"].Value = productId;
product.Fields["Product Industry Ids"].Value = industryIds;
product.Fields["Category Ids"].Value = categoryIds;
}
finally
{
product.Editing.EndEdit();
}
}
}
}
// when done
message.InnerText = "Complete";
}
catch (Exception ex)
{
message.InnerText = "Error reading file";
}
}
}
The problem is that when a description field has commas, like "Product is an effective, preventative biofungicide," it gets split as well and throws off the index, so categoryIds = data[8] gets the wrong value.
The spreadsheet is data that is provided by our client, so I would rather not require the client to edit the file unless necessary. Is there a way I can handle this in my code? Is there a different way I can read the file that won't split everything by comma?
I suggest use Ado.Net, If the field's data are inside quotes and it will parse it like a field and ignore any commas inside this..
Code Example:
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

How can i get the location of a textfile

I need to get the location of a certain textfile before i user it with sytem.IO methods. I am trying to get an application working on all computer but when i switch between computers it seems to change my D: drive memory pen to and F: drive so the location changes. This is what I have been trying to use:
baseLocation = Application.ExecutablePath;
string UsernameTXT = #PublicVariables.baseLocation + "//userName.txt"
StreamReader user_Login = new StreamReader(UsernameTXT);
string PasswordTXT = #PublicVariables.baseLocation + "//userPass.txt"
StreamReader pass_Login = new StreamReader(PasswordTXT);
while (pass_Login.Peek() != -1)
{
user = user_Login.ReadLine();
pass = pass_Login.ReadLine();
if ((user == textBox1.Text) && (pass == textBox2.Text))
{
MessageBox.Show("Login successful!",
"Success");
}
}
I know this part is wrong:
string UsernameTXT = #PublicVariables.baseLocation + "//userName.txt"
StreamReader user_Login = new StreamReader(UsernameTXT);
string PasswordTXT = #PublicVariables.baseLocation + "//userPass.txt"
StreamReader pass_Login = new StreamReader(PasswordTXT);
its just that i have no idea what to use there instead.
Any help is appreciated.
You may want to have a look at the Path.Combine method that allows you to attach a file name to a path to get the fully qualified file name.
In your example, assuming the files are stored in your Application.StartupPath:
baseLocation = Application.StartupPath;
string usernameFile = Path.Combine(baseLocation, "userName.txt");
string passwordFile = Path.Combine(baseLocation, "userPass.txt");
NOTE: Don't ever store unencrypted passwords!
To read and match a user name with a password, you can then do the following:
var userNameFound = false;
ar passwordMatches = false;
try
{
var ndx = 0
var passwords = File.ReadAllLines(passwordFile);
foreach (var userName in File.ReadAllLines(usernameFile))
{
userNameFound = userName.Equals(textBox1.Text);
if (userNameFound && ndx < passwords.Length)
{
passwordMatches = passwords[ndx].Equals(textBox2.Text);
break; // no need to search further.
}
ndx++;
}
}
catch (FileNotFoundException)
{
MessageBox.Show("Failed to open files", "Error");
}
And report the result like this:
if (userNameFound)
{
if (passwordMatches)
MessageBox.Show("Login successful!", "Success");
else
MessageBox.Show("Incorrect password", "Error");
}
else
{
MessageBox.Show("Incorrect login", "Error");
}
Use this code to get the removable drive name and append your text file name to it
DriveInfo[] ListDrives = DriveInfo.GetDrives();
string driveName=stirng.Empty;
foreach (DriveInfo Drive in ListDrives)
{
if (Drive.DriveType == DriveType.Removable)
{
driveName=Drive.Name;
}
}

sqlBulk insert C#

I have a page where I want to upload a CSV file from my computer to database on the server and I have my opentext that looks like the following
using (StreamReader sr = File.OpenText(#"c:\users\workstationUsername\FileName.csv"))
This works fine on my local machine but when I push this to the server it tries to read the server's C Drive and I want it to read the physical file location that is sitting on the desktop of the user's computer not the server, when they click browse and upload..
Thank you
below is the complete code:
if (IsPostBack)
{
// SetDefaultDates();
Boolean fileOK = false;
String dateString = DateTime.Now.ToString("MMddyyyy");
String UserName = User.Identity.Name;
String path = Server.MapPath("~/Uploads/CSVs/");
string stringpath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
String fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
stringpath = stringpath + fileName;
String LocationToSave = path + "\\" + fileName;
if (FileUpload1.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = { ".csv" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
//FileUpload1.PostedFile.SaveAs(LocationToSave + dateString + "-" + FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(LocationToSave);
Label1.Text = "File " + FileUpload1.FileName + " uploaded!";
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(stringpath))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
}
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.WriteToServer(dt);
}
}
}
catch (Exception ex)
{
Label1.Text = "File " + FileUpload1.FileName + " could not be uploaded." + ex.Message;
}
}
else
{
Label1.Text = "Cannot accept files of this type. " + FileUpload1.FileName;
}
}
SetDefaultDates();
}
If you have a FileUpload control, then instead of using (StreamReader sr = File.OpenText(#"c:\users\workstationUsername\FileName.csv")) which obvously is pointing to the server's hard drive you can do this:
(StreamReader sr = new StreamReader(fileUploadControl.FileContent))
//Do your stuff
You can't access the client's hard drive. That's a major security concern. You'll need to upload the file to your server, and read it from there.
It doesnt make sense to have a static read to the local machine, rather get user to upload it then update the database, this code is very limiting and has a high security risk. Rather create a steamreader object get the user to upload it then use the steam reader to process the csv.

Compare csv file with with a column of a table

I have a csv file like this :
george,
nick,
mary,
john,
micheal
The user can make a file he likes. So he could have 4 or 5 or 28 lines for example.
I have an other csv file, that I assigned it to a ArrayList named fileList1 . This file is an agenda.
If a name in the agenda isn't in the csv, that will be given, then print a message.(this is what I need to find). The point is that both the csv can be dymanical. The number of lines is not standar.
I have also a table, colB[]. This table has the list of files that will compare with columns.
The problem is that I can not select a specific column in the arraylist because it is an arraylist.
ArrayList fileList1 = new ArrayList();
string stringforData;
private void button1_Click(object sender, EventArgs e)
{
// opens **BROWSE**
string filename = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox1.Text = filename;
// Read the file and display it line by line.
string line;
System.IO.StreamReader file1 = new System.IO.StreamReader(textBox1.Text); //reads the path from textbox
stringforData = file1.ReadLine();
while ((line = file1.ReadLine()) != null)
{
// bazei stoixeia mesa ston pinaka
fileList1.Add(line.Split(';'));//split the file and assign it in //the fileList1
}
file1.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
this.textBox2.Clear();
string[] colB = new string[];
for (int j = 0; j < colB.Length; j++)
{
if (Path.GetExtension(colB[j]) == ".csv")
{
string path = Path.GetDirectoryName(textBox1.Text);
string g = Path.Combine(path, colB[j]);
textBox2.Text += "the path is " + g + " " + Environment.NewLine;
System.IO.StreamReader gi = new System.IO.StreamReader(g);
string itemss;
ArrayList ArrayForLists=new ArrayList();
while ((itemss = gi.ReadLine()) != null)
{
ArrayForLists.AddRange(itemss.Split(';'));// assign to the arraylist the list that we are searching
}
}
It seems that an ArrayList is not a good option because you can't select the desired column. Why not use a free C# CSV parser:
http://www.filehelpers.com/
Found from here:
CSV parser/reader for C#?
In the link above there's also an example that loads a CSV into a DataTable, which gives you the option to reference a column (as opposed to an ArrayList).
Edit:
I've pasted the code from the given link:
static DataTable CsvToDataTable(string strFileName)
{
DataTable dataTable = new DataTable("DataTable Name");
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + Directory.GetCurrentDirectory() + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\""))
{
conn.Open();
string strQuery = "SELECT * FROM [" + strFileName + "]";
OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
adapter.Fill(dataTable);
}
return dataTable;
}

Categories

Resources