So im nearly there, just need to load the information from my text file in notepad which is saved like so:
item1
item2
item3
item4
My first attempt was this:
gridProfiles.Columns.Add("App Name", "Active");
int i = 0;
foreach(char snif in "D:\\ProfileAppName.txt")
{
gridProfiles.Rows.Add();
gridProfiles.Rows[i].Cells[0].Value = snif;
i++;
}
But this just loaded the file name into the text file
My next attempt was:
gridProfiles.Columns.Add("App Name", "Active");
int i = 0;
foreach (string snif in "D:\\ProfileAppName.txt")
{
string[] values = snif.Split(' ');
int j = 0;
foreach (string value in values)
{
gridProfiles.Rows.Add();
gridProfiles.Rows[i].Cells[0].Value = snif;
j++;
}
}
i++;
But i get the error "cannot convert type 'char' into 'string'
Can anyone help me? im nearly there but cant get my finger on it
You are looping all chars in this string: "D:\\ProfileAppName.txt". I assume you want to loop all lines in the file. Then you can use File.ReadLines:
foreach(string line in File.ReadLines("D:\\ProfileAppName.txt"))
{
gridProfiles.Rows.Add();
gridProfiles.Rows[i].Cells[0].Value = line;
i++;
}
The read the content of the file you could do this:
int i = 0;
foreach(string row in File.ReadAllLines("D:\\ProfileAppName.txt"))
{
if (i % 2 == 0)
gridProfiles.Rows.Add();
gridProfiles.Rows[i / 2].Cells[i % 2].Value = line;
i++;
}
Related
I need your help.
I want to make a program where I give a number and it increments it as many times as I said and write output into a .txt file. I have an issue with writing it because it only writes one output. I know basics but I have never worked with more complicated coding, only a few games, and simple apps.
int baseNumber = int.Parse(tbBase.Text);
int codeNumber = int.Parse(tbCodeNumber.Text);
int[] codes = new int[codeNumber];
int count = 0;
string link = "https://www.roblox.com/groups/";
for (int i =0; i < codes.Length; i++)
{
codes[i] = baseNumber++;
}
foreach (int element in codes)
{
string text= $"{link}{Convert.ToString(codes[count])}";
System.IO.File.WriteAllText(#"D:\TextFiles\WriteText.txt", text);
count++;
}
you can use this code . You wrote the number of for loops in the file, which is wrong. Put the text in a string and put it in the file
int baseNumber = int.Parse(tbBase.Text);
int codeNumber = int.Parse(tbCodeNumber.Text);
int[] codes = new int[codeNumber];
for (int i = 0; i < codes.Length; i++)
{
codes[i] = baseNumber++;
}
int count = 0;
string text = "";
string link = "https://www.roblox.com/groups/";
foreach (int element in codes)
{
text += $"{link}{Convert.ToString(codes[count])}";
count++;
}
string fileName = #"D:\WriteText.txt";
if (File.Exists(fileName))
System.IO.File.AppendAllText(fileName, text);
else
System.IO.File.WriteAllText(fileName, text);
Read text file for editing
public void ReadFile(string fileName)
{
string[] lines = System.IO.File.ReadAllLines(fileName);
// Display the file contents by using a foreach loop.
string text = "";
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
text += line + Environment.NewLine;
Console.WriteLine("\t" + line);
}
}
I have a DataTable with 1 column and a List of DataTables with 2 columns each.
I want to compare the Value of the DataTable with the first 6 digits of the Value of each DataTable in the List row by row.
This is my Code:
for(int fs = 0; fs < dataTable.Rows.Count; fs++)
{
for(int fs2 = 0; fs < dataTableList.Count; fs2++)
{
for(int fs3 = 0; fs3 < dataTableList[fs2].Rows.Count; fs3++)
{
if(dataTable.Rows[fs]["columnName"].ToString().Equals(dataTableList[fs2].Rows[fs3]["otherColumnName"].ToString().Substring(0,6)))
{
//do sth.
}
}
}
}
When the program reaches if(dataTable.Rows[fs]["columnName"].ToString().Equals(dataTableList[fs2].Rows[fs3]["otherColumnName"].ToString().Substring(0,6))) it stops and i get an System.ArgumentOutOfRangeException error.
Does anybody know what I am doing wrong? When I MessageBox the substring it is working.
So, first of all, I suggest refactoring this monstrosity to foreach loops.
foreach(var row in dataTable.Rows)
{
foreach(var otherDataTable in dataTableList)
{
foreach(var otherRow in otherDataTable.Rows)
{
/* ... */
}
}
}
And then checking if the string you're trying to get a substring of actually has length of 6 or more.
const int compareLength = 6;
const string columnName = "columnName";
const string otherColumnName = "otherColumnName";
foreach(var row in dataTable.Rows)
{
foreach(var otherDataTable in dataTableList)
{
foreach(var otherRow in otherDataTable.Rows)
{
var value = row[columnName].ToString();
var otherValue = otherRow[otherColumnName].ToString();
if(otherValue.Length >= compareLength &&
value == otherValue.Substring(0, compareLength))
{
/* Do something. */
}
}
}
}
My bet is that Substring call when the compared value was shorter than 6 was the problem. See if this helps.
I write some data into csv file from List but some list indexes has empty string but another indexes has value
in these cases the data compared with another list wrote in the same csv file
this is my csv file opened using excel sheet
in the third column there exist ID for the the second column cell so in the coming rows i want to detect the name of the ID based on previous rows
like in row 3 it's ID is 19 and name is I/O so in the 7th row the ID is 19 and want to fill the second cell now
info : the IDs is already known above and any next ID will be exist before
by the follwing code.
bool isInList = ms.IndexOf(ShapeMaster) != -1;
if (isInList)
{
savinglabelnamefortextbox = t.InnerText;
string replacement =
Regex.Replace(savinglabelnamefortextbox, #"\t|\n|,|\r", "");
xl.Add("");
dl.Add(replacement);
ms.Add(ShapeMaster);
}
and I use the following code to write to the csv file
using (StreamWriter sw = File.CreateText(csvfilename))
{
for (int i = 0; i < dl.Count; i++)
{
var line = String.Format("{0},{1},{2}", dl[i], xl[i],ms[i]);
sw.WriteLine(line);
}
}
Try this
for (int x = 0; x < ms.Count; x++)
{
if (xl[x] != "")
{
continue;
}
else if (xl[x] == "")
{
for (int y = 0; y<xl.Count; y++)
{
if (ms[y] == ms[x])
{
xl[x] = xl[y];
break;
}
}
continue;
}
}
I'm attempting to parse a text file containing data that is being used on a remote FTP server. The data is delimited by an equals sign (=) and I'm attempting to load each row in to two columns in a DataGridView. The code I have written works fine except for when an equals character is thrown into the second column's value. When this happens, regardless of specifying the maximum count as being 2. I'd prefer not to change the delimiter if possible.
Here is the code that is being problematic:
dataGrid_FileContents.Rows.Clear();
char delimiter = '=';
StreamReader fileReader = new StreamReader(fileLocation);
String fileData = fileReader.ReadToEnd();
String[] rows = fileData.Split("\n".ToCharArray());
for(int i = 0; i < rows.Length; i++)
{
String str = rows[i];
String[] items = str.Split(new char[] { delimiter }, 1, StringSplitOptions.RemoveEmptyEntries);
if (items.Length == 2)
{
dataGrid_FileContents.Rows.Add(items[0], items[1]);
}
}
fileReader.Close();
And an example of the file being loaded:
boats=123
cats=234-f
cars==1
It works as intended for the first two rows and then ignores the last row as it ends up creating a String[] with 1 element and two String[]s with zero elements.
Try the following. It will capture the value before and after the first '=', correctly parsing the cars==1 scenario.
String[] items = str.Split(new char[] { delimiter }, 2, stringSplitOptions.None);
A different solution, if you want everything after the first equals then you could approach this problem using string.IndexOf
for(int i = 0; i < rows.Length; i++)
{
String str = rows[i];
int pos = str.IndexOf(delimiter);
if (pos != -1)
{
string first = str.Substring(0, pos-1);
string second = str.Substring(pos + 1);
dataGrid_FileContents.Rows.Add(first, second);
}
}
Just read all items delimeted by '=' in row.
Then iterate over items, and check, that item not empty, than use this prepared data to write
here illustrated snippet
http://dotnetfiddle.net/msVho2
and your snippet can be transformed to something like bellow
dataGrid_FileContents.Rows.Clear();
char delimiter = '=';
using(StreamReader fileReader = new StreamReader(fileLocation))
{
string[] data = new string[2];
while(true)
{
string row = fileReader.ReadLine();
if(row == null)
break;
string[] items = row.Split(delimiter);
int data_index = 0;
foreach(string item in items)
{
if(data_index >= data.Length)
{
//TODO: log warning
break;
}
if(!string.IsNullOrWhiteSpace(item))
{
data[data_index++] = item;
}
}
if(data_index < data.Length)
{
//TODO: log error, only 1 item in row
continue;
}
dataGrid_FileContents.Rows.Add(data[0], data[1]);
}
}
I will do what I can to get a snipit of the txt files on here for you to look at. most of them are class and it will take a bit of work for me to do that. The idea is to take a txt file with say a list of over 500 places run them against a list of 50 places and pull out the ones that match. As I said I have tried many diffrent ways, well all the ones I know, and I can not seem to get it to work right. I am trying to take the following code and have it do the above action. Does that help.
InPutBox = Input.Text;
int x = 1;
var lines = Input.Text.Split(new string[] { Environment.NewLine },StringSplitOptions.None);
for (var index = 0; index < lines.Length; index++)
{
var line = lines[index];
do
{
x++;
System.Console.WriteLine("'{0}'", InPutBox);
bool test1 = InPutBox.StartsWith("TAG");
bool test2 = InPutBox.EndsWith("TAG");
if (test1 && test2)
{
int first = InPutBox.IndexOf("TAG");
int last = InPutBox.LastIndexOf("TAG");
InPutBox = InPutBox.Substring(first, last - first);
}
}
while (x < 50);
System.Console.WriteLine("'{0}'", line);
if ((line.StartsWith("TAG") && line.EndsWith("TAG")))
{
MessageBox.Show("These are errors in line" + index + ": " + line);
break;
}
}