I am trying to write to a file with around 20 fields. That part works. The first field needs to be unique (can't have duplicates). I cannot figure out how to take only the first field(column) and compare it to the rest in that column. Also I am not sure how to get the variable from the file. The field is a combination of the first and last name. That works just fine but I need to run through the userName and compare it to the rest of them. If another one is the exact same, I need a number added to one of them.
This is what I started but I am not sure now to continue:
class userName
{
public string Name(string userName)
{
string initialUserName
string tempUserName = string.Empty;
}
}
This is how I create the user name:
username = firstName.Substring(0, 4) + lastName.Substring(0, 4);
Without knowing the specifics of how you are writing these "fields," im assuming a single line (row) of your file contains all 20 fields. Hopefully you have delimited each of these fields. You should be able to get all the variables in the first column by reading the lines of the file, one at a time, and using the String.Split method to get a string array containing all of your 20 fields. Simply compare the first array member to your new value, if its equal then append a number to the new string, continue this until all rows are parsed.
Hope this will help. Use streamreader and streamwriter to read and write the text file. Create hashtable store the column read value in it. If you find same content just don't write it.
Related
jaja. folks, my first post was too extensive, let me try again. i think it is important to always be polite when asking for help and to fully communicate one's motivations, so one liners would not be the best vehicle to do this but i will adapt to how things are done in this forum. chances are it will be helpful to split my question into modules.
i have this piece of code in easylanguage that generates one unique text file with a unique filename every time one of four different types of events takes place (every individual text file serves as its own separate log entry). i need to convert this code to c# (i will use this code inside the ninjatrader trading platform), using streamwriter ot any other c# solutions that would allow me to generate unique text files with filenames created dynamically that would include some string inputs, variables and date and time with a similar format to the following:
// pass in a string containing line to be written to the file
method void recordevent(string msg)
variables:
string filepath;
begin
// create file name, including a directory based upon the symbol
//
// note: symbol should not contain characters that are not valid in file names
// indicator name should not contain invalid characters for a file name
// add whatever other parameters desired
filepath = string.format("{0}\{1}_{2}_{3:yyyyMMddhhmmss}_{4}_{5}.txt",
iprimarydirectory,
filnamplusymtic,
gronam,
datetime.now,
casnum,
numtostr(price,2));
print(filepath);
sw = streamwriter.create(filepath);
sw.autoflush = true;
sw.writeline(msg);
sw.close();
end;
[note: primary directory, file name plus symbol ticker and group name are string inputs to be defined by the user while case number is a string variable to be calculated by the program. i use this information to make sure filenames are unique and to keep files sorted by symbol ticker and time they were generated.]
very well, i hope this version of my initial question will be more understandable and manageable. thanks to all, regards.
I'm not going to try and decipher your entire post. If the question is just how do you append a line to a file (creating it if it doesnt exist), then its pretty simple in c sharp:
private void WriteFile(string text)
{
// lock a generic object to ensure only one thread is accessing the following code block at a time
lock (lockObj)
{
string filePath = Path.Combine(#"C:\ntlogs\",$"{DateTime.Now.ToString("yyyyMMdd HHmmss")}.txt");
File.AppendAllText(filePath, text);
}
If there are other specific problems you face then create a separate question and ask about that specifically without all the additional information
I'm getting stuck clicking a listbox item (the items in my listbox is .txt files in a folder) and displaying the values in the .txt file.
the values in the .txt files are all seperated with a "," and I want each Split item to display in labels on my form.
my file path is: System.AppDomain.CurrentDomain.BaseDirectory + "data"
my .txt file names are the names of the selected item in my listbox.
I have a basic idea of what should happen, but I have no clue how to express this in code.
My Code:
private void custList_MouseClick(object sender, MouseEventArgs e)
{
string foldr = System.AppDomain.CurrentDomain.BaseDirectory + "data";
string file = custList.SelectedIndex.ToString();
}
Thanx in advance
Before i go on answering this question, please read How to ask. This will help you better understand this community and ask better questions(to get better support).
Next on, do some research. From a first glance, it looks like you are asking someone to do the homework for you. Anyways, i am not here to be tough on you. I will point you out a few things. Try to understand them and utilize them.
Note that even though it may seem as such but i am not a fan of spoon-feeding so be sincere and do your research.
Let's start with your text file. As you mentioned, it contains values. C#, being a versatile & mature language has a lot of functions,methods,classes pre-built to help boost your programming experience. Such a method is ReadAllText, a part of the File class. In the simplest words, this method opens a text file, reads it, returns it's value. A sample use of this method could be :
string TextFromFile = File.ReadAllText(File_Path_Goes_Here);
Moving on... Your text file has multiple values separated by comma(,). In such cases, each value needs to read as a separate value upon retrieving or displaying. So, you want a List of the values, end of story. In C#, you have a wide range of generic lists to use from. As the values in the text file are simple strings, you can use a List<string> in this regard. A basic usage example of List<string> would be :
List<string> TestList1 = new List<string>();
TestList1.Add("First Value"); TestList1.Add("Second Value");
///or
List<string> TestList1 = new List<string>(){ "First Value", "Second Value" };
In your particular case, File.ReadAllLines is worth an example. The method opens a text file, reads it, closes it. Of course it returns the value read from the text file, as an array. So, when passing values to the generic list, you can simply make use of this method. Example :
...... new List<string>(File.ReadAllLines(Path_Of_File_Goes_Here));
The only twist here is that the values in your text file are in a line(maybe) and also are separated by comma. So, what do you think should work here ? ReadAllText or ReadAllLines ? I will leave it upto you.
Once values are read from the file, we can make use of the Split function to split the values upon each occurrence of a comma(,). A simple example :
List<string> NameList = "Josh,Riley".Split(',').ToList<string>();
And last but not the least, the headline of the question which doesn't seem to have anything to do with the post itself, here's what you can take a look at :
Control Click Event
ListBox.GetItemText
Tip: The SelectedItem property of the ListBox class returns or sets the selected item of a listbox.
I hope this has been helpful. Do pay attention to all that's mentioned above. It may be a bit hard to follow up with at first, but remember, Consistency is the hallmark of the unimaginative.
....Yeah, that's not my quote. Gotcha!
I don't know where you want to show the values of your text file, so I will just provide you what you need to retrieve those informations.
To get values from your file:
public string[] GetValues()
{
string[] values;
using(StreamReader sr = new StreamReader(Path.Combine(foldr, file))
{
string text = sr.ReadToEnd();
values = text.Split(',');
}
return values;
}
Then you can show them using an array:
public void Main()
{
string[] values = GetValues();
foreach(var value in values)
{
Console.WriteLine(value);
}
}
Hope this helps.
I am new to C# but am working on a project at work. The task is to copy an array of values from one application to the clipboard and then to store those values in a list of objects in C#. I have created private properties for each field represented by the columns in the copied data, but i cannot figure out how to parse the data from the clipboard and store it in each property. Hopefully this makes sense. I'm having trouble even figuring out where to begin despite extensive searching. Any help would be greatly appreciated.
As suggested by Jack A. in the comments, use String.Split().
Something like...
if (Clipboard.ContainsText())
{
string str = Clipboard.GetText();
string[] values = str.Split("\t".ToCharArray());
// ... do something with "values" ...
xxx.aaa = values[0];
xxx.bbb = values[1];
xxx.ccc = values[2];
// etc...
}
else
{
MessageBox.Show("No Text in the Clipboard!");
}
You should probably check to make sure the right number of columns were present after splitting, though:
if (values.Length == 5)
{
// ... do something with "values" ...
}
I used this recently in another project: http://joshclose.github.io/CsvHelper/
Although you aren't using a CSV per se, you are using delimited data and it allows you to specify the delimeter. If you convert your text into a text reader similar to this post: In C#, how can I create a TextReader object from a string (without writing to disk), it will easily transfer the data to an object of your choosing once you have mapped it
I want to send multi attach in email, but have problem with those. When I put all files what want to send in one string always get error, but when put one file in one attach inside of loop thing work.
Now I have problem with copying one part of string in to another strings, don't know how to do that, do you have some solution?
Example:
txtattach.Text = "d:\\folder\\file1,d:\\folder\\file2,d:\\folder\\file3";
want to get 3 strings with context of location without "," that I can easy put it in loop.
use the split function:
string[] paths = txtattach.Text.Split(',');
One way to do this is using the Split method so you easily can iterate over the items in a loop:
foreach(var filename in txtAttach.Text.Split(','))
{
// Do something with filename
}
I'm about to build a solution to where I receive a comma separated list every night. It's a list with around 14000 rows, and I need to go through the list and select some of the values in the list.
The document I receive is built up with around 50 semicolon separated values for every "case". How the document is structured:
"";"2010-10-17";"";"";"";Period-Last24h";"Problem is that the customer cant find....";
and so on, with 43 more semicolon statements. And every "case" ends with the value "Total 515";
What I need to do is go through all these "cases" and withdraw some of the values in the "cases". The "cases" is always built up in the same order and I know that it's always the 3, 15 and 45'th semicolon value that I need to withdraw.
How can I do this in the easiest way?
I think you should decompose this problem into smaller problems. Here are the steps I'd take:
Each semi-colon separated record represents a single object. C# is an object-oriented language. Stop thinking in terms of .csv records and start thinking in terms of objects. Break up the input into semi-colon delimited records.
Given a single comma-separated record, the values represent the properties of your object. Give them meaningful names.
Parse a comma-separated record into an object. When you're done, you'll have a collection of objects that you can deal with.
Use C#'s collections and LINQ to filter your list based on those cases that you need to withdraw. When you're done, you'll have a collection of objects with the desired cases removed.
Don't worry about the "easiest" way. You need one way that works. Whatever you do, get something working and worry about optimizing it to make it easiest, fastest, smallest, etc. later on.
Assuming the "rows" are lines and that you read line by line, your main tool should be string.Split:
foreach (string line in ... )
{
string [] parts = line.split (';');
string part3 = parts[2];
string part15 = parts[14];
// etc
}
Note that this is a simple approach that will fail if the content of any column can contain ';'
You could use String.Split twice.
The first time using "Total 515"; as the split string using this overload. This will give you an array of cases.
The second time using ";" as the split character using this overload on each of the cases. This will give you a data array for each case. As the data is consistent you can extract the 3rd, 15th and 45th elements of this array.
I'd search for an existing csv library. The escaping rules are probably not that easily mapped to regex.
If writing a library myself I'd first parse each line into a list/an array of strings. And then in a second step(probably outside of the csv library itself) convert the stringlist to a strongly typed object.
A simple but slow approach would be reading single characters from the input (StringReader class, for example). Write a ReadItem method that reads a quote, continues to read until the next quote, and then looks for the next character. If it is a newline of semicolon, one item has been read. If it is another quote, add a single quote to the item being read. Otherwise, throw an exception. Then use this method to split up the input data into a series of items, each line stored e.g. in a string[number of items in a row], lines stored in a List<>. Then you can use this class to read the CSV data inside another class that decodes the data read into objects that you can get your data out of.