I have these textboxes where the user enters data and then presses a button to process the data. Now the data entered by the user is alot and to give the user some slack I want to make it possible whenever you press the button, the application saves the data, so when you close the application and start it back up again the textboxes are filled with the last entered data.
I was thinking about using a .txt file to save the data. Only I have found some difficulties with this. One of the problems is that I keep getting a messagebox from the microsoft .NET Framework everytime I try to run my application. The messagebox says the Index was outside the bounds of the array. Even though I think my code doesn't exceed the bounds of my array.
And here is the code that I use:
First I declared an array and filled it with variables that contain the content of the textboxes:
string[]settings = new string[5];
settings[0] = openKey;
settings[1] = secretKey;
settings[2] = statusRequestPath;
settings[3] = statusRequestAPI;
settings[4] = setSeconds.ToString();
Then I use the following code to write the data to a text file.
using (StreamWriter writeFile = new StreamWriter(#"C:\Audio Silence Detector\AudioSilenceDetector.txt"))
{
foreach (string line in settings)
{
writeFile.WriteLine(line);
}
}
And to put the text of the .txt file back in the application I have put this in the formload:
string[] lines = System.IO.File.ReadAllLines(#"C:\Audio Silence Detector\AudioSilenceDetector.txt");
tbOpenKey.Text = lines[0];
tbSecretKey.Text = lines[1];
tbStatusRequestPath.Text = lines[2];
tbStatusRequestAPI.Text = lines[3];
tbSeconds.Text = lines[4];
I changed my code to this and it seems to have fixed the issue I was having:
if (lines.LongLength == 5)
{
tbOpenKey.Text = lines[0];
tbSecretKey.Text = lines[1];
tbStatusRequestPath.Text = lines[2];
tbStatusRequestAPI.Text = lines[3];
tbSeconds.Text = lines[4];
}
The problem is in file loading.
string[] lines = System.IO.File.ReadAllLines(#"C:\Audio Silence Detector\AudioSilenceDetector.txt");
You can not be sure that lines now contains 5 elemetns. You probably should check for that.
if(lines.Length == 5)
{
tbOpenKey.Text = lines[0];
tbSecretKey.Text = lines[1];
tbStatusRequestPath.Text = lines[2];
tbStatusRequestAPI.Text = lines[3];
tbSeconds.Text = lines[4];
}
else
{
MessageBox.Show("Input Data is Wrong");
}
Related
I'm trying to set up a simple command for entering all callers into a .txt file, everything is working out nicely except for the part where I want to loop through the list and check that no one is trying to enter more than once, it's not causing any problems to the application itself but it's not doing what it's supposed to do.
Any help would be much appreciated.
string filePath = Secret.Secrets.fileDestination;
var username = msg.Author.Username;
//ulong
var ID = msg.Author.Id;
string IDout = ID.ToString();
List<string> entries = File.ReadAllLines(filePath).ToList();
if(entries.Contains(IDout))
{
await msg.Channel.SendMessageAsync($"{msg.Author.Mention}, you have already been entered.");
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"Denied entry for {msg.Author.Mention}");
return;
}
entries.Add($"{username}, {ID}");
File.WriteAllLines(filePath, entries);
await msg.Channel.SendMessageAsync($"{msg.Author.Mention} has been entered!");
I am trying to work through a school assignment that has us use a C# program to parse data from a CSV file and add it to a table in a local database. When I try to run the program though, the method I am using fails to parse any of the data into the object.
Here is the method I am using:
//Parse CSV line
public bool ParseCSVline(string aLine)
{
try
{
string[] fields = aLine.Split(',');
this.Item_ID = int.Parse(fields[0]);
this.Invent_id = int.Parse(fields[1]);
this.Itemsize = fields[2];
this.Color = fields[3];
this.Curr_price = decimal.Parse(fields[4]);
this.Qoh = int.Parse(fields[5]);
return true; //if everything parsed, return true
}
catch (Exception ex)
{
Console.Write("Failed to Parse");
return false; //if a parse failed, return false
}
When running the program the method keeps throwing the Exception instead of actually parsing the data. For clarity, here is the section in the Main program that is calling everything:
/Step 2 - Open input file
//Set where the file comes from
string filepath = #"C:\Users\Karlore\Documents\School\SAI-430\";
string filename = #"NewInventory.csv";
//Open reader
StreamReader theFile = new StreamReader(filepath + filename);
//Step 3 - Create an object to use
Item theItem = new Item();
//Step 4 - Loop through file and add to database
while (theFile.Peek() >= 0)
{
//Get one line and parse it inside the object
theItem.ParseCSVline(filename);
//Check to see if item is already there
if (theItem.IsInDatabase(connection))
{
continue;
}
else
{
//Add the new item to the database if it wasn’t already there
theItem.AddRow(connection);
}
} //end of while loop
If anyone can point out where I may have made an error, or point me in the right direction I would appreciate it.
Replace the line:
theItem.ParseCSVline(filename);
by:
theItem.ParseCSVline(theFile.ReadLine());
I'm new to C# and I'm trying to implement a button.visible true/false based on the contents of a txt file. Everything I've written to date is unstable at best. This is for a Winform stand alone application in the main dialog box.
In an ideal world it seems it should be simpler. I want the code to open Permissions.txt, which I know I am successfully accessing as the MessageBox will show the first name in the list, and compare the Environment.UserName with all of the names in the .txt file. Once the button is displayed it opens a new dialog box.
Anyone willing to teach a newcomer. I've been searching for a while and I don't see it.
I have also tried working with File.Readlines with no success.
Thank you in advance for any assistance you're willing to provide.
Frank Pytel
public void hideWidget()
{
//gets the users login name from the system
string newName = userNameOnly();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(dataFolder + "\\Permissions.txt");
//This next bit called Original Code works on my local when I access it, when accessed from a server, but not for other users.
//Original code
//while ((line = file.ReadLine()) != null)
//{
// if (line == newName)
// {
// WidgetForm.Visible = true;
// }
// else
// {
// WidgetForm.Visible = false;
// }
// //MessageBox.Show(line);
// counter++;
//}
//file.Close();
//This is where I am at currently. Again it's not picking up all of the names in the .txt file.
while (file.ReadLine() != null)
{
//string line;
string line = file.ReadLine();
if (newName == file.ReadLine())
{
WidgetForm.Visible = false;
}
else
{
WidgetForm.Visible = true;
}
int counter = 0;
//MessageBox.Show(line);
//MessageBox.Show(file.ReadLine());
counter ++;
}
//file.Close();
}
EDITED....
Also if there is anyone that could possibly explain how string line; is being set to my user name. That is how it should have been set, but I've never told it line == newName in the original code. I thought that is what the While is for. To check to see if they are equal..
FINAL EDIT.
Here is what I got to work. Thanks #Bedford.
This portion goes directly below the Form1 class
string[] lines = File.ReadAllLines(dataFolder + "\\Permissions.txt");
This is the logic behind the hideWidget() button
public void hideWidget()
{
//Make all userNames available to the logic
string newName = userNameOnly();
//variable to decide if userExists is true/false
bool userExists;
//Loop through all of the userNames in the file and see if it matches the userName login
while (lines != null)
{
//Decide to make the button available if userExists does exist in the file
if (lines != null)
{
userExists = lines.Any(ln => ln == newName);
WidgetForm.Visible = userExists;
}
//Do nothing if the userName does not match anyone in the Permissions.txt file. The button default Visible is false
else
{
}
return;
}
}
I'm posting this snippet so that others might benefit from it. Thanks again #Bedford. This NEWB really appreciates the assistance. HAGD!! :-)
You can read all the lines from a file with the File.ReadAllLines static method, and then use a LINQ query to check whether any of the lines match the user name:
string[] lines = File.ReadAllLines(Path.Combine(dataFolder, "Permissions.txt"));
bool userExists = lines.Any(ln => ln == newName); // or any comparison you like
// use the bool variable to set the visibility
WidgetForm.Visible = userExists;
Need help formatting a seperated .txt file in C#. I have a text file that contains a directory listing and looks like as follows when I open up in notepad or ultra-edit. First column is date and time, next column is the size of file in bytes, third column is the username and fourth column is the name of the file. Each column is separated by one or more spaces, and the filename column at the end can contain spaces in the filename. They consist of more directories and the total amount of lines in the file is about 200,000.
Directory of V:\word
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILE NAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
Directory of V:\word\administrators
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILENAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
My goal is to try and add the path of the directory (ex. V:\Word or other directories) in a fixed format at the end of the filename. So Once you see the "Directory V:\word" then you know every line after and up until a new Directory, should show that path at the end of the filename. This would be considered the fifth column.
Here is some code, but I still need to help. I am able to get V:\word at the end of the file, but how do I read the new directory and append that to the end of the lines for all subsequent lines?
private void button1_Click(object sender, EventArgs e)
{
var sbText = new StringBuilder(10000);
string currLine = " Directory of V:\\word ";
try
{
using (StreamReader Reader = new StreamReader(#"C:\V.txt"))
{
while (!Reader.EndOfStream)
{
if (currLine != " Directory of V:\\word ")
{
MessageBox.Show("No Directory");
}
else
{
sbText.AppendLine(Reader.ReadLine() + "V:\\word");
}
}
// When all of the data has been loaded, write it to the text box in one fell swoop
richTextBox1.Text = sbText.ToString();
using (StreamWriter Writer = new StreamWriter(#"C:\NEWFILE.txt"))
{
Writer.WriteLine(sbText);
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occured. " + ex.Message);
}
Here's a fairly straight-forward approach--which defines a simple class that represents your data, and parses each line into a class instance. It's efficient, and the results can easily be written to a new file, queried, or displayed:
void Main()
{
var lines = ReadFile();
lines.ToList().ForEach (Console.WriteLine);
}
IEnumerable<Line> ReadFile()
{
using (var reader = new StreamReader(File.OpenRead(#"file.txt")))
{
const string directoryPrefix = " Directory of ";
Regex splittingRegex = new Regex(#"\s+", RegexOptions.Compiled);
string directory = null;
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.TrimEnd();
if (line.StartsWith(directoryPrefix))
{
directory = line.Substring(directoryPrefix.Length);
continue;
}
// The "6" parameter means the regex will split the string into 6 parts at most--leaving the last column (filename) unsplit
var lineParts = splittingRegex.Split(line, 6);
yield return new Line{ Date = lineParts[0], Time = lineParts[1], Period = lineParts[2], Bytes = lineParts[3], User = lineParts[4], Filename = Path.Combine(directory, lineParts[5]) };
}
}
}
// Define other methods and classes here
class Line
{
public string Date{get;set;}
public string Time {get;set;}
public string Period {get;set;}
public string Bytes {get;set;}
public string User {get;set;}
public string Filename {get;set;}
}
Note: This is derived from a couple helper methods for parsing simple text files. One of my earlier revisions include the helper methods, which might be of use to you (but aren't quite suited for this due to the need to remember the directory value).
You're incrementing wCurrLine but never resetting it. I think you want to reset it after each directory?
You're not incrementing totalLines, but then displaying it in label2. I think you should be incrementing it.
How do you check if the input line of text is a directory entry? If your text is consistent as presented, you could check the first letter of each row as it's read in and check if it is the letter 'D'.
You need to AppendLine not Append to put the carriage returns back in
Ok, well i'm basically trying to find a certain line withing "Users.txt"
Heres my code so far.
if (ok == "b" || ok == "B")
{
using (StreamWriter w = File.AppendText("Users.txt"))
{
//Test
Out.WriteLine("Please state the username");
string user = Console.ReadLine();
Out.WriteLine("Checking..");
if (w.Equals(user))
{
Out.WriteLine("Username is taken");
}
Thread.Sleep(pause);
Out.WriteLine("Please state the password for the user");
string pass = Console.ReadLine();
Logger(user, pass, w);
// Close the writer and underlying file.
w.Close();
Out.WriteLine("Checking..");
Out.WriteBlank();
Thread.Sleep(pause);
Out.WriteLine("Anything else Mr." + Environment.UserName + " ?");
}
string choice = Console.ReadLine();
if (choice == "no")
{
Boot();
}
if (choice == "yes")
{
Console.Clear();
Console.Title = "Administrator Panel";
Panel();
}
}
want it to see if the "user" is taken, then stop them from executing the process.
Thanks for the help.
Try reading (StreamReader with File.Open) each existing username into an array/List and then comparing user input against that list.
Your current code doesn't actually read anything since you're using a StreamWriter with File.AppendText which just lets you write to the end of a file.
Examples:
Reading File into a List
List<string> users = new List<string>();
using (StreamReader r = new StreamReader("Users.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
users.Add(line);
}
}
...
string user = Console.ReadLine();
Out.WriteLine("Checking..");
if (users.Contains(user))
{
Out.WriteLine("Username is taken");
}
There are various problems with your code. Let's see if we can break it down one piece at a time.
using (StreamWriter w = File.AppendText("Users.txt"))
This code would be useful if you wanted to open "Users.txt" and append text to it. Since you want to open a file and read from it, you need to use a different object, the StreamReader object:
using (StreamReader r = File.Open("Users.txt"))
Next, you want to check if the given Username is in the file. You're doing:
if (w.Equals(user))
{
Out.WriteLine("Username is taken");
}
This isn't going to work. You are comparing a StreamWriter object with a String object. They will never be equal.
What you need to do instead is change the order of your program like this:
First, read the entire contents of the file into memory. Then, outside of the Using statement, process your user input and your username/password checking.
Let's assume the file is organized like this:
username,password
username2,password2
johnsmith,mysecretcode
janedoe,blahblah
You could, for example, read each line into a Dictionary object, where the Key is the username and the Value is the password.
Dictionary<String, String> myDictionary = new Dictionary<String, String>
// Example of adding ONE username/password to the dictionary
myDictionary.Add("username", "password");
Then, checking for the username would be as simple as
bool containsUsername = myDictionary.ContainsKey(username);
And checking the password would be:
bool doesPasswordMatch = myDictionary[username] == givenPassword;
Give it a shot! C# is a great language to learn.