List values are not being stored - c#

Can someone please tell me what I'm missing, the class reads values from a text file and should store them for other use, I can see the values with
Console.Write(eachCell[0]) but I can't save the values. I've tried using
string[] and List<string> but no luck. It should store the values being read to a list or array but so far it is not. Nothing shows on the console.
class test
{
public void tryOut()
{
#region file.read
try
{
string fileLocation = #"shelfInfo.txt";
List<string> cells = File.ReadAllLines(fileLocation).ToList();
aray(cells);
}
catch
{
new FileNotFoundException();
}
#endregion
}
public void aray(List<string> cells)
{
string[] t = new string[20];
string[] k = new string[20];
string a = "", b = "", c = "", d = "";
int i = 0;
foreach (string cell in cells)
{
string[] eachCell = cell.Split('#', '\t', '\n');
a = t[0] = eachCell[0].ToString(); //Consol.Write on eachCell directly shows the right values.
b = t[1] = eachCell[1].ToString();
c = t[2] = eachCell[2].ToString();
d = t[3] = eachCell[3].ToString();
for (; i < eachCell.Length; i++)
{
k[i] = a; //should store the values from eachCell
}
}
Console.Write(" " + a + " " + b + " " + " " + c + " " + d); //means the value are being receivedbut no stored
}
}
// contents of text file
//A11[1]# A12[0]# A13[1]# A14[1]#
//A21[1]# A21[1]# A23[0]# A24[0]#
//A31[1]# A32[0]# A33[1]# A34[1]#
//A41[1]# A41[1]# A43[0]# A44[0]#
I'd also, appreciate any tips on exception handling.

Your program doesn't return anything because you use the following code.
catch { new FileNotFoundException(); }
Console.Write return nothing just because the exception is caught but it doesn't throw a new exception. There is an exception because eachCell doesn't contain 4 elements and you try to access the element. In fact, you don't have to do the try-catch unless you want to handle this exception manually. If the file isn't there, a FileNotFoundException would already be thrown automatically. Change the tryOut method as the following.
public void tryOut()
{
#region file.read
var fileLocation = #"Path";
aray(File.ReadAllLines(fileLocation).ToList());
#endregion
}
public static void aray(List<string> cells)
{
List<string> t = new List<string>();
foreach (string cell in cells)
{
string[] eachCell = cell.Split('#', '\t');
foreach (var e in eachCell)
{
t.Add(e);
}
}
foreach (var e in t)
{
Console.WriteLine(e);
}
}

Related

c# return loop without using foreach

Hello I need some help in my Code
Code in test.cs:
public class test
{
public string[] content ={
"Username:Peter",
"ID:1",
"Username:Nike",
"ID:2"};
public IEnumerable<string> Name
{
get
{
var username = content.Where(a => a.StartsWith("Username:")).ToList();
for(int i = 0; i < username.Count(); i++)
{
yield return username[i].Substring(username[i].IndexOf(":") +1); // Displays the usernames (Peter, Nike)
}
}
}
public IEnumerable<string> ID
{
get
{
var username = content.Where(a => a.StartsWith("ID:")).ToList();
for (int i = 0; i < username.Count(); i++)
{
yield return username[i].Substring(username[i].IndexOf(":") +1); // Displays the ID (1, 2)
}
}
}
}
Code in main file:
var test = new test();
foreach (var l in test.Name)
treeView1.Nodes.Add(l);
All works fine it displays the names right, but I dont want use foreach i want add it like:
treeView1.Nodes.Add("Name: " + test.Name + " ID:" + test.ID);
thanxs for helping
You can convert to array and then use a for loop (assuming you're sure that elements are in pairs):
var names = test.Name.ToArray();
var ids = test.Id.ToArray();
for (var i = 0; i < names.Length; i++)
{
treeView1.Nodes.Add("Name: " + names[i] + " ID: " + ids[i]);
}
firstly:
public class test
{
public string[] content ={
"Username:Peter",
"ID:1",
"Username:Nike",
"ID:2"};
public Dictionary<string, string> contents;
public Dictionary<string, string> Contents
{
get
{
if (contents == null)
{
InitContents();
}
return contents;
}
}
private void InitContents()
{
contents = new Dictionary<string, string>();
for (var i = 0; i < content.Length; i++)
{
contents.Add(GetValue(content[i]), GetValue(content[i + 1]));
i++;
}
}
private string GetValue(string data)
{
return data.Substring(data.IndexOf(":", StringComparison.Ordinal) + 1);
}
public IEnumerable<string> GetContents()
{
return Contents.Select(x => "Name: " + x.Key + " ID:" + x.Value);
}
}
then use:
treeView1.Nodes.AddRange(yourTests.Contents.Select(x=>new TreeNode("Name:"+x.Key+"Id:"+x.Value))))

Set a string on a string referenced by string array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
string db;
ComboBox fieldBox = new ComboBox()
TextBox ValueBox = new TextBox()
ListBox dbValues = new ListBox()
private void LoadDB()
{
//Structure
string myStruct = "NAME\nAGE\nSEX\nSKILL
db = "John\t20\tMale\tNoob\n
Joe\t20\tMale\tMedium\n
Jessica\t27\tFemale\tExpert\n
John\t21\tMale\tMedium
";
//Load struct to combobox
string[] mbstr = myStruct.Split('\n');
for (int i = 0; i < mbstr.Length; i++)
{
fieldBox.Items.Add(mbstr[i]);
}
string[] db2 = db.Split('\n');
for (int i = 1; i < db2.Length - 1; i++)
{
//Display name and age in combobox
dbValues.Items.Add(db2[i].Split('\t')[0] + " - " + db2[i].Split('\t')[1]);
}
}
void ValueBoxKeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode != Keys.Enter)
return;
db.Split('\n')[dbValues.SelectedIndex].Split('\t')[fieldBox.SelectedIndex] = valueBox.Text;
MessageBox.Show("Value set: " +
db.Split('\n')[dbValues.SelectedIndex + 1].Split('\t')[fieldBox.SelectedIndex]
+ " to " + valueBox.Text + ".");
}
This is where it fails:
db.Split('\n')[dbValues.SelectedIndex].Split('\t')[fieldBox.SelectedIndex] = valueBox.Text;
I tried this, and tried to assign to db, but not working though. My original string is unchanged.
I do not want to convert to list and string back, i want to change directly.
How can i do this?
Your first problem is your string: unless you use # escaping you can't have your string cross multiple lines, and if you use # escaping you can't do \t or \n and retain their escaped meaning of tab and newline.
The second problem is a fundamental misunderstanding of the .NET string, string's are immutable. Split will create an array, there is no reference back to the original string, or the second array your splitting. You would need to do something like:
[TestClass]
public class StringTest
{
public TestContext TestContext { get; set; }
[TestMethod]
public void RewriteString()
{
var str = "Garry\t19\tMale\tNoob\n" +
"Joe\t25\tMale\tMedium\n" +
"Gary\t33\tFemale\tExpert";
var rows = str.Split('\n');
var columns = rows[0].Split('\t');
columns[0] = "Jerry";
rows[0] = string.Join("\t", columns);
str = string.Join("\n", rows);
TestContext.WriteLine(str);
}
}
Test Name: RewriteString
Test Outcome: Passed
Result StandardOutput: TestContext Messages:
Jerry 19 Male Noob
Joe 25 Male Medium
Gary 33 Female Expert
Would really hope there would be an easier way to do this, possibly with a Regex?
Now to really look at your (new) question. I have refactored exactly what you have, as I do not know your data situation I'm not entirely sure using a string as a database is a good idea: (this will compile without any references because of the use of dynamic).
public class SomeView
{
string db;
dynamic fieldBox = null;
dynamic valueBox = null;
dynamic dbValues = null;
dynamic MessageBox = null;
private void LoadDB()
{
//Structure
string myStruct = "NAME\nAGE\nSEX\nSKILL";
db = "John\t20\tMale\tNoob\n" +
"Joe\t20\tMale\tMedium\n" +
"Jessica\t27\tFemale\tExpert\n" +
"John\t21\tMale\tMedium";
//Load struct to combobox
string[] mbstr = myStruct.Split('\n');
for (int i = 0; i < mbstr.Length; i++)
{
fieldBox.Items.Add(mbstr[i]);
}
string[] db2 = db .Split('\n');
for (int i = 1; i < db2.Length - 1; i++)
{
var data = db2[i].Split('\t'); //expensive only do once
//Display name and age in combobox
dbValues.Items.Add(data[0] + " - " + data[1]);
}
}
protected string Transform(string value, int row, int column, string replacement, out string old)
{
var rows = value.Split('\n');
var columns = rows[row].Split('\t');
old = columns[column];
columns[column] = replacement;
rows[row] = string.Join("\t", columns);
return string.Join("\n", rows);
}
void ValueBoxKeyDown(object sender, dynamic e)
{
if (e.KeyCode != "enter")
return;
string old;
string newValue = this.Transform(db, dbValues.SelectedIndex, fieldBox.SelectedIndex, valueBox.Text, out old);
MessageBox.Show("Value set: " + old + " to " + valueBox.Text + ".");
}
}
So this is better:
public class SomeView
{
dynamic fieldBox = null;
dynamic valueBox = null;
dynamic dbValues = null;
dynamic MessageBox = null;
private List<Person> People = new List<Person>();
private void LoadDB()
{
//Structure
string myStruct = "NAME\nAGE\nSEX\nSKILL";
string db = "John\t20\tMale\tNoob\n" +
"Joe\t20\tMale\tMedium\n" +
"Jessica\t27\tFemale\tExpert\n" +
"John\t21\tMale\tMedium";
//Load struct to combobox
string[] mbstr = myStruct.Split('\n');
for (int i = 0; i < mbstr.Length; i++)
{
fieldBox.Items.Add(mbstr[i]);
}
People.Clear();
foreach(var row in db.Split('\n'))
{
var columns = row.Split('\t');
Person p = new Person();
p.Name = columns[0];
p.Age = int.Parse(columns[1]);
p.Sex = (Person.Sexs)Enum.Parse(typeof(Person.Sexs), columns[2]);
p.SkillLevel = (Person.SkillLevels)Enum.Parse(typeof(Person.SkillLevels), columns[2]);
People.Add(p);
dbValues.Items.Add(string.Format("{0}-{1}", p.Name, p.Age);
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public enum Sexs
{
Male,
Female
}
public Sexs Sex { get; set; }
public enum SkillLevels
{
Noob,
Medium,
Expert
}
public SkillLevels SkillLevel { get; set; }
}
void ValueBoxKeyDown(object sender, dynamic e)
{
if (e.KeyCode != "enter")
return;
Person p = this.People[dbValues.SelectedIndex];
switch((int)fieldBox.SelectedIndex)
{
case 0: p.Name = valueBox.Text; break;
case 1: p.Age = int.Parse(valueBox.Text); break;
case 2: p.Sex = (Person.Sexs)Enum.Parse(typeof(Person.Sexs), valueBox.Text); break;
case 3: p.SkillLevel = (Person.SkillLevels)Enum.Parse(typeof(Person.SkillLevels), valueBox.Text); break;
default: throw new NotImplementedException();
}
MessageBox.Show("Value set: " + old + " to " + valueBox.Text + ".");
}
}
However this is still garbage, since if you have a strongly typed data set you can actually bind this to form controls without directly manipulating the item.
https://msdn.microsoft.com/en-us/library/c8aebh9k(v=vs.110).aspx
You cannot change the return-value of a method returning a string as strings are immutable. What you can do instead is the following:
string myDatabase =
"Garry\t19\tMale\tNoob\n" +
"Joe\t25\tMale\tMedium\n" +
"Gary\t33\tFemale\tExpert";
var tmp = "";
foreach(var line in myString.Split('\n')) {
tmp = tmp + Regex.Replace(line, "^.*?(?=\\t)", myReplaceText);
}
myString = tmp;
This regex will search for everything before the very first tab within every line, replaces it by "Jerry"and and concatenates every so replaced line into myString.

Reading delimited text file?

I am trying to read from a delimited text file, but everything is returned in in one row and one column.
My connections string is
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
Path.GetDirectoryName(#textBox1txtPath.Text) + ";" +
"Extended Properties=\"text;HDR=YES;IMEX=1;Format=Delimited(|)\"");
And my text file reads:
ItemNumber|ProductStatus|UPC
0000012|closed|2525
Please assist
Okay, so one option would be to take a different approach. Consider the following code:
// read the entire file and store each line
// as a new element in a string[]
var lines = File.ReadAllLines(pathToFile);
// we can skip the first line because it's
// just headings - if you need the headings
// just grab them off the 0 index
for (int i = 1; i < lines.Length; i++)
{
var vals = lines[i].Split('|');
// do something with the vals because
// they are now in a zero-based array
}
This gets rid of that monstrosity of a connection string, eliminates the overhead of an Odbc driver, and drastically increases the readability of the code.
i don't know exactly what do you need, but you can do this:
if you have string str with the whole text in it you can do
string[] lines = str.Split('\n');// split it to lines;
and then for each line you can do
string[] cells = line.Split('|');// split a line to cells
if we take it to the next level we can do:
public class line
{
public int ItemNumber { get; set; }
public string ProductStatus { get; set; }
public int UPC { get; set; }
public line(string currLine)
{
string[] cells = currLine.Split('|');
int item;
if(int.TryParse(cells[0], out item))
{
ItemNumber = item;
}
ProductStatus = cells[1];
int upc;
if (int.TryParse(cells[2], out upc))
{
UPC = upc;
}
}
}
and then:
string[] lines = str.Substring(str.IndexOf("\n")).Split('\n');// split it to lines;
List<line> tblLines = new List<line>();
foreach(string curr in lines)
{
tblLines.Add(new line(curr);
}
It's right in the framework -- TextFieldParser. Don't worry about the namespace, it was originally a shim for folks converting from VB6, but it's very useful. Here's a SSCCE that demonstrates its use for a number of different delimiters:
class Program
{
static void Main(string[] args)
{
var comma = #"one,""two, yo"",three";
var tab = "one\ttwo, yo\tthee";
var random = #"onelol""two, yo""lolthree";
var parser = CreateParser(comma, ",");
Console.WriteLine("Parsing " + comma);
Dump(parser);
Console.WriteLine();
parser = CreateParser(tab, "\t");
Console.WriteLine("Parsing " + tab);
Dump(parser);
Console.WriteLine();
parser = CreateParser(random, "lol");
Console.WriteLine("Parsing " + random);
Dump(parser);
Console.WriteLine();
Console.ReadLine();
}
private static TextFieldParser CreateParser(string value, params string[] delims)
{
var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(ToStream(value));
parser.Delimiters = delims;
return parser;
}
private static void Dump(TextFieldParser parser)
{
while (!parser.EndOfData)
foreach (var field in parser.ReadFields())
Console.WriteLine(field);
}
static Stream ToStream(string value)
{
return new MemoryStream(Encoding.Default.GetBytes(value));
}
}

C# List & Sort URLs by FileName

I want to make this:
anywhere.com/file/mybirthday.avi
anywhere.com/file/yourbirthday.avi
somewhere.com/file/mybirthday.avi
somewhere.com/file/yourbirthday.avi
To This:
anywhere.com/file/mybirthday.avi
somewhere.com/file/mybirthday.avi
##############
anywhere.com/file/yourbirthday.avi
somewhere.com/file/yourbirthday.avi
I found filenames with regex. And I sorted them. So my codes are here:
private void button1_Click(object sender, EventArgs e)
{
string gelenler = textBox2.Text;
gelenler = gelenler.Replace("\r\n\r\n", "\r\n");
string cikti = string.Empty;
string regex = #"([^\/\\]+\.\w+)$";
string[] parca = Regex.Split(gelenler, "\r\n");
string[] parca2 = new string[parca.Length];
for (int i = 0; i < parca.Length; i++)
{
string ad = match(regex, parca[i]);
parca2[i] = ad;
}
Array.Sort(parca2);
for (int j = 0; j < parca2.Length; j++)
{
for (int i = 0; i < parca2.Length; i++)
{
if (parca2[i].IndexOf(match(regex,parca[j]))!=-1)
{
textBox1.Text += parca[i] + Environment.NewLine;
parca[i] = "";
}
textBox1.Text += "#############" + Environment.NewLine;
}
}
}
private string match(string regex, string html, int i = 1)
{
return new Regex(regex, RegexOptions.Multiline).Match(html).Groups[i].Value.Trim();
}
But didn't working. Any ideas ?
//Sorry my English
I think always the best idea is to use existing .net framework stuff, as in this case Path.GetFileName:
var strings = new[]
{
"anywhere.com/file/mybirthday.avi",
"anywhere.com/file/yourbirthday.avi",
"somewhere.com/file/mybirthday.avi",
"somewhere.com/file/yourbirthday.avi"
};
strings = strings.OrderBy(x => Path.GetFileName(x)).ToArray();
foreach (var s in strings)
{
Console.WriteLine(s);
}
Console.ReadKey();
I think you mean grouping the files; in which case the following code can be used:
IEnumerable<IGrouping<string, string>> groups = strings.GroupBy(x => Path.GetFileName(x)).OrderBy(g => g.Key);
foreach (var group in groups)
{
foreach (var str in group)
{
Console.WriteLine(str);
}
Console.WriteLine("#############");
}
You should use the Uri class. Use the Segements property in order to get the file name (it will be the last segment).
var uris = new[]
{
new Uri("http://anywhere.com/file/mybirthday.avi"),
new Uri("http://anywhere.com/file/yourbirthday.avi"),
new Uri("http://somewhere.com/file/mybirthday.avi"),
new Uri("http://somewhere.com/file/yourbirthday.avi")
};
var filename = uris.OrderBy(x => x.Segments[x.Segments.Length - 1]).ToArray();
foreach (var f in filename)
{
Console.WriteLine(f);
}

In file, if line contains substring, get all of the line from the right

I have a file. Each line looks like the following:
[00000] 0xD176234F81150469: foo
What I am attempting to do is, if a line contains a certain substring, I want to extract everything on the right of the substring found. For instance, if I were searching for 0xD176234F81150469: in the above line, it would return foo. Each string is of variable length. I am using C#.
As a note, every line in the file looks like the above, having a base-16 number enclosed in square brackets on the left, followed by a hexadecimal hash and a semicolon, and an english string afterwards.
How could I go about this?
Edit
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Form1 box = new Form1();
if(MessageBox.Show("This process may take a little while as we loop through all the books.", "Confirm?", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
XDocument doc = XDocument.Load(#"C:\Users\****\Desktop\books.xml");
var Titles = doc.Descendants("Title");
List<string> list = new List<string>();
foreach(var Title in Titles)
{
string searchstr = Title.Parent.Name.ToString();
string val = Title.Value;
string has = #"Gameplay/Excel/Books/" + searchstr + #":" + val;
ulong hash = FNV64.GetHash(has);
var hash2 = string.Format("0x{0:X}", hash);
list.Add(val + " (" + hash2 + ")");
// Sample output: "foo (0xD176234F81150469)"
}
string[] books = list.ToArray();
File.WriteAllLines(#"C:\Users\****\Desktop\books.txt", books);
}
else
{
MessageBox.Show("Aborted.", "Aborted");
}
}
I also iterated through every line of the file, adding it to a list<>. I must've accidentally deleted this when trying the suggestions. Also, I am very new to C#. The main thing I am getting stumped on is the matching.
You could use File.ReadLines and this Linq query:
string search = "0xD176234F81150469:";
IEnumerable<String> lines = File.ReadLines(path)
.Select(l => new { Line = l, Index = l.IndexOf(search) })
.Where(x => x.Index > -1)
.Select(x => x.Line.Substring(x.Index + search.Length));
foreach (var line in lines)
Console.WriteLine("Line: " + line);
This works if you don't want to use Linq query.
//"I also iterated through every line of the file, adding it to a list<>." Do this again.
List<string> li = new List<string>()
//However you create this string make sure you include the ":" at the end.
string searchStr = "0xD176234F81150469:";
private void button1_Click(object sender, EventArgs e)
{
foreach (string line in li)
{
string[] words;
words = line.Split(' '); //{"[00000]", "0xD176234F81150469:", "foo"}
if (temp[1] == searchStr)
{
list.Add(temp[2] + " (" + temp[1] + ")");
// Sample output: "foo (0xD176234F81150469)"
}
}
}
string file = ...
string search= ...
var result = File.ReadLines(file)
.Where(line => line.Contains(search))
.Select(line => line.Substring(
line.IndexOf(search) + search.Length + 1);
Unfortunately, none of the other solutions worked for me. I was iterating through the hashes using foreach, so I would be iterating through all the items millions of times needlessly. In the end, I did this:
using (StreamReader r = new StreamReader(#"C:\Users\****\Desktop\strings.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines++;
if (lines >= 6)
{
string[] bits = line.Split(':');
if(string.IsNullOrWhiteSpace(line))
{
continue;
}
try
{
strlist.Add(bits[0].Substring(10), bits[1]);
}
catch (Exception)
{
continue;
}
}
}
}
foreach(var Title in Titles)
{
string searchstr = Title.Parent.Name.ToString();
string val = Title.Value;
string has = #"Gameplay/Excel/Books/" + searchstr + ":" + val;
ulong hash = FNV64.GetHash(has);
var hash2 = " " + string.Format("0x{0:X}", hash);
try
{
if (strlist.ContainsKey(hash2))
{
list.Add(strlist[hash2]);
}
}
catch (ArgumentOutOfRangeException)
{
continue;
}
}
This gave me the output I expected in a short period of time.

Categories