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;
}
}
Related
I want to check if the given Password is the password which is locking the Excel-File.
Here is how i tried it:
var DepartmentStream = new FileStream(Deparment, FileMode.Open);
var EmplyoeeStream = new FileStream(Employee, FileMode.Open);
var options = new LoadOptions {Password = "ExamplePassword123"};
DepartmentGrid = new Workbook(DepartmentStream); // set as a Workbook property and doesn't need a password
try
{
EmployeeGrid = new Workbook(EmplyoeeStream , options); // set as a Workbook property
}
catch (Exception ex)
{
EmployeeGrid= null;
}
if (EmployeeGrid == null)
{
MessageBox.Show("The given password is wrong!", "Wrong password",);
return;
}
How can i fix this, so that if the EmployeeGrid's (set as a Workbook property) password isn't the same as the given password the MessageBox get showed and the code leaves the method?
Your code looks to me OK, what's wrong with it? Your current code is trying to load an encrypted (password protected) file with the given password. If your code is not doing what you want, kindly do elaborate your needs, so we could help you accordingly. I will also write another sample code for your complete reference:
e.g
Sample code:
string m_documentFile = "e:\\test2\\EncryptedBook1j.xls";
//Get the password list to store into arrays.
string[] m_passwordList = { "001", "002", "003", "004", "005", "006", "007", "008" };
Workbook _workBook;
int i = 0;
int ncnt = 0;
//Check if the file is password protected.
FileFormatInfo fft = FileFormatUtil.DetectFileFormat(m_documentFile);
bool check = fft.IsEncrypted;
RetryLabel:
try
{
if (check)
{
LoadOptions loadOps = new LoadOptions();
for (i = ncnt; i < m_passwordList.Length; i++)
{
loadOps.Password = m_passwordList[i];
_workBook = new Workbook(m_documentFile, loadOps);
MessageBox.Show("Opened Successfully with the Password:" + m_passwordList[i]);
break;
}
}
}
catch (Exception ex)
{
if (ex.Message.CompareTo("Invalid password.") == 0)
{
MessageBox.Show("Invalid Password: " + m_passwordList[i] + " ,trying another in the list");
ncnt = i + 1;
goto RetryLabel;
}
}
PS. I am working as Support developer/ Evangelist at Aspose.
I'd like to automatically generate diffrent folder structures (As a preperation for new Video/Film-Editing projects). It also allows to add special folders like After Effects and Photoshop to every folder-structure.
It should read the structure from a config file and then create the folders.
My current code looks like this:
if(tbPath.Text == "_______________________________________________________"
|| tbConfigPath.Text == "_______________________________________________________"
|| tbPath.Text == ""
|| tbConfigPath.Text == "")
{
System.Windows.MessageBox.Show("You didn't enter a valid Path.", "Invalid Path", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
//List for the paths
List<string> paths = new List<string>();
List<string> finalpaths = new List<string>();
string outPath = tbPath.Text;
//Where to get the config from
string configPath = tbConfigPath.Text;
string line = "";
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(configPath);
while ((line = file.ReadLine()) != null)
{
paths.Add(line);
}
file.Close();
for (int i = 0; i < paths.Count(); i++)
{
finalpaths.Add(outPath + paths[i]);
}
//----------------Folder Generatring------------
for (int i = 0; i < paths.Count(); i++)
{
Directory.CreateDirectory(finalpaths[i]);
}
// Add After Effects
if (cbAE.IsChecked == true)
{
string AEpath = outPath + "\\AfterEffects";
Directory.CreateDirectory(AEpath);
}
// Add Photoshop
if (cbAE.IsChecked == true)
{
string PSpath = outPath + "\\Photoshop";
Directory.CreateDirectory(PSpath);
}
System.Windows.MessageBox.Show("The folders where generated successfully", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
pgStartUp pgStart = new pgStartUp();
NavigationService.Navigate(pgStart);
But I feel like this isn't really efficient. Is there any better way?
When you use:
Directory.CreateDirectory(path);
This line creates all or missing directories in the path string you are passing as a parameter. So you don't need anything else.
All your logic should be focused on creating a correct path string, taking into account the root directory and things like that.
As coders we often think in code and try to solve everything with it.
If the base structure is the same, create the folder structure once, zip it up, and then:
Directory.CreateDirectory(tbPath.Text);
ZipFile.ExtractToDirectory("yadayada.zip", tbPath.Text);
// Add After Effects
if (cbAE.IsChecked == true)
{
string AEpath = outPath + "\\AfterEffects";
Directory.CreateDirectory(AEpath);
}
// Add Photoshop
if (cbAE.IsChecked == true)
{
string PSpath = outPath + "\\Photoshop";
Directory.CreateDirectory(PSpath);
}
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();
}
}
I am trying to create a program that will replace a string inside .txt file.
heres the trick. I am replacing the string in the file if they are checked,
but when I do an alternate check its still replacing the other.
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
DateTime now = DateTime.Now;
List<string> allFiles = new List<string>();
AddFileNamesToList(sourceFolder, allFiles);
if (listView1.CheckedItems.Count != 0)
{
foreach (String file in allFiles)
{
for (int x = 0; x <= listView1.CheckedItems.Count - 1; x++)
{
if (file.Contains(listView1.CheckedItems[x].Text))
{
MessageBox.Show("File contains: " + listView1.CheckedItems[x].Text);
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, Searchbar.Text, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content); writer.Close();
}
else
{
}
}
catch
{
}
}
}
}
}
}
else
{
MessageBox.Show("Please Check the files you want to rename");
}
}
public static void AddFileNamesToList(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
try
{
foreach (string fileName in fileEntries)
{
allFiles.Add(fileName);
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
}
}
}
I am still confused about what you are trying to do, but to simplify things, why don't you, when you populate the ListView with the files in the directory, add the file path (or a file object) to the tag property of the ListViewitem?
That way, when you loop through the checked items, you can just retrieve the file directly instead of having to loop through two Lists at once.
Something like:
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
AddFileNamesToList(sourceFolder);
if (listView1.CheckedItems.Count == 0)
{
MessageBox.Show("Please Check the files you want to rename");
return;
}
for (int x = 0; x < listView1.CheckedItems.Count; x++)
{
var file = listView1.CheckedItems[x].Tag.ToString()
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, SearchWord, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content);
writer.Close();
}
}
catch
{
}
}
}
}
Sorry for the indenting and also if this doesn't work straight as is, I haven't tested this.
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.