Checking a TXT Doc against anther TXT Doc - c#

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;
}
}

Related

Why is my logic not adding the quotes back to the CSV File for the columns after the First one?

I am using hashmaps to store CSVFile1 and compare it to CSVFile2. CSVFile1 has a column of customers to remove while CSVFile2 has all of the completed data (which has more then 1 column and that is why I am only comparing dataArray2[0]). Once I compare I only rewrite the files that are NOT in the CSVFile1 to a file called CSVFileFinal.
The issue is that some of the data has commas inside of fields and when I read the file it take them out once I try and rewrite. My goal is to rewrite the data with the quotes back around the commas in the fields which I "split" at.
I have managed to get the First column (the most important one) to split and replace the quotes perfectly! But for whatever reason my second loop is messing up and not checking the columns after that correctly. I believe it is simply the placing of my code.
This is the logical statement/placement in question:
if (dataArray2[i].Contains(","))
{
string x = "\"" + dataArray2[i] + "\"";
record = x;
}
I know the logic works because if you look at my entire source code; the code posted works for the first column and works in the 2nd IF statement for If i == 0 meaning if it's the 1st columns. But how or where do I place that to work for the others afterward?
Can anyone help figure out where to place this for the following columns?
It should be a simple copy and pasting of the code I have but I've been unable to figure it out. Thank you!
int count = 0;
while (!CSVFile2.EndOfData)
{
if (!badCustomers.ContainsKey(dataArray2[0]))
{
String record = null;
for(int i = 0; i < dataArray2.Length; i++)
{
if(i == 0)
{
if (dataArray2[i].Contains(","))
{
string x = "\"" + dataArray2[i] + "\"";
record = x;
}
else
record = dataArray2[i];
} else
{
record = record + "," + dataArray2[i];
}
}
count++;
if( count % 50 == 0)
{
Console.WriteLine(count);
}
output.WriteLine(record);
}
dataArray2 = CSVFile2.ReadFields();
}
The above code works but does not consider the later columns after the first one to replace this quotes- this code is what should fix the ones after the first column but for whatever reason it does not. Why?
if (!badCustomers.ContainsKey(dataArray2[0]))
{
String record = null;
for(int i = 0; i < dataArray2.Length; i++)
{
if(i == 0)
{
if (dataArray2[i].Contains(","))
{
string x = "\"" + dataArray2[i] + "\"";
record = x;
}
else
record = dataArray2[i];
} else
{
if (dataArray2[i].Contains(","))
{
string x = "\"" + dataArray2[i] + "\"";
record = x;
}
else
record = record + "," + dataArray2[i];
}
}
What I believe you are asking is for this:
int count = 0;
while (!CSVFile2.EndOfData)
{
if (!badCustomers.ContainsKey(dataArray2[0]))
{
String record = String.Empty;
for(int i = 0; i < dataArray2.Length; i++)
{
if (dataArray2[i].Contains(","))
{
string x = "\"" + dataArray2[i] + "\"";
record += x;
}
else
{
record += dataArray2[i];
}
if (i < dataArray.Length -1)
{
record += ",";
}
}
count++;
if( count % 50 == 0)
{
Console.WriteLine(count);
}
output.WriteLine(record);
}
dataArray2 = CSVFile2.ReadFields();
}
This loops through each line from the input, adding quotes around commas. You may have to tweak it to meet your final needs, but this should be a start.
The reason it was only ever doing it for your first column is the if(i == 0). This means the code would only ever execute for the first iteration (your first column).

How to decrement the index of a line in an array of strings?

I am making a code that decrements the line index in an array of strings. My array is like this:
1.ExampleFirst\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
2.ExampleSecond\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
and so on. The lengths of the lines are not the same.
I want the text to be like this:
0.ExampleFirst\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
1.ExampleSecond\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
I have made this code:
int s = 0;
while(s < lineCounter.Count())
{
if (int.TryParse(lineCounter[s].Substring(0, 1), out v) == true && lineCounter[s] != "\n")
{
int m = int.Parse(lineCounter[s].Substring(0,1));
lineCounter[s].Remove(0, lineCounter[s].IndexOf(".")).Insert(0, (m - 1).ToString());
Console.WriteLine(lineCounter[s]);
}
else
Console.WriteLine(lineCounter[s]);
s++;
The "if" is executed only when the line contains the number and when the line is not a new line. The else is executed to write the other lines in the array.(I'm using console.writeLine to see the results. I know I have to change that part)
When I execute this code, I get the following exception in the "if" statement:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index and length must refer to a location within the string.
To me this means that "if" is executed even when the new line between the last line of the first text block and the first line of the second text block is encountered. I can't explain why. Help please!
Declaring dotIndex with combination of string.Remove() and string.Insert() may do the trick.
string[] lineCounter = new string[]{
"1.ExampleFirst\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n\n",
"2.ExampleSecond\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n\n"
};
for (int i = 0; i < lineCounter.Count(); ++i) {
int dotIndex = lineCounter[i].IndexOf('.');
if (dotIndex < 1) //must be at least in the position of 2 or above
continue;
int lineIndex = 0;
if (int.TryParse(lineCounter[i].Substring(0, dotIndex), out lineIndex)) { //if can be parsed
lineIndex--; //decrement lineIndex
lineCounter[i] = lineIndex.ToString() + lineCounter[i].Remove(0, dotIndex);
}
}
I prefer to use for-loop to make the loop more definite, but you could change that to while/do.
This works fine in my PC. Output:
Edit:
All the results should be in the lineCounter. If you want to see them along the function, you could do:
for (int i = 0; i < lineCounter.Count(); ++i) {
int dotIndex = lineCounter[i].IndexOf('.');
if (dotIndex < 1) { //must be at least in the position of 2 or above
//Print here
continue;
}
int lineIndex = 0;
if (int.TryParse(lineCounter[i].Substring(0, dotIndex), out lineIndex)) { //if can be parsed
lineIndex--; //decrement lineIndex
lineCounter[i] = lineIndex.ToString() + lineCounter[i].Remove(0, dotIndex);
}
//Print here also
}
you probably want this:
string[] lineCounter=new string[]{
"1.ExampleFirst\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n",
"\n",
"2.ExampleSecond\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n",
"\n"
};
int v = 0;
int s = 0;
while (s < lineCounter.Count())
{
if (int.TryParse(lineCounter[s].Substring(0, 1), out v) == true && lineCounter[s] != "\n")
{
int m = int.Parse(lineCounter[s].Substring(0, 1));
Console.WriteLine(lineCounter[s].Remove(0, lineCounter[s].IndexOf(".")).Insert(0, (m - 1).ToString()));
}
else
Console.WriteLine(lineCounter[s]);
s++;
}
I believe you may be having issues with empty lines on the string array.
Maybe something like this works for you.
IEnumerable<string> ShiftIndexes(IEnumerable<string> lines) {
foreach (string line in lines) {
if (!string.IsNullOrEmpty(line) && char.IsDigit(line, 0)) {
int dotPos = line.IndexOf('.');
int index = int.Parse(line.SubString(0, dotPos));
yield return (index - 1).ToString() + line.SubString(dotPos);
}
else
yield return line;
}
}
And then use it like this:
string[] shiftedLines = ShiftIndexes(originalLines).ToArray();

Auto Incrementing file names?

I have a list of files like so
abc.txt
pas.txt
tempr.txt
What I would like to do is to append english alphabets to theese file names ..
the result should look like this
abc_a.txt
pas_b.txt
tempr_c.txt
This process should continue till the last character (i.e 'z'). if there are more files then the file names would become
abc_a.txt
pas_b.txt
tempr_c.txt
.................
filename_z.txt
anotherfilename_a001.txt
Notice that the counter was again reset to the first character except an integer was attached to it.
This is the code that i have right now. Please note that it is NOT working ..
string alphabets= "abcdefghijklmnopqrstuvwxyz";
List<string> filenames = new List<string>();
filenames.Add("test1.txt");
filenames.Add("newfile.cs");
filenames.Add("test2.txt");
filenames.Add("newfile2.cs");
string currentFileNmae = string.Empty;
foreach(string s in filenames) {
char usedAlphabet = new char();
for(int i = 0;i<=alphabets.Length-1;i+=11) {
usedAlphabet.Dump();
alphabets[i].Dump();
if(usedAlphabet != alphabets[i] )
{
if(currentFileNmae!= s)
{
string.Format("{0}--{1}",s,alphabets[i]).Dump();
usedAlphabet = alphabets[i];
currentFileNmae = s;
}
}
break;
}
}
I am part of a team that's building a file renamer tool for our internal purposes and hence i need this code. This is part of the our enumertation functionality that we have planned.
Please suggest.
thanks
Try starting here:
using System.Diagnostics;
using System.IO;
string filename = #"C:\Foo\Bar.txt";
for (int count = 0; count < 100; count++)
{
char letter = (char)((int)'a' + count % 26);
string numeric = (count / 26) == 0 ? "" : (count / 26).ToString("000");
Debug.Print(Path.GetFileNameWithoutExtension(filename) + "_" + letter + numeric + Path.GetExtension(filename));
}
Substitute your own loop to go through the filenames and use Path to manipulate the pieces/parts of the names.
The renaming, IIRC, can be handled by File.Move. Surround it with a try/catch to implement the name collision logic.
Had no coffee yet, but this should do.
List<string> files = new List<string>();
int charIndex = 0;
int numericIndex = -1;
foreach (var file in files.Select(path => new FileInfo(path)))
{
// Create new Filename - This may needs some tuning
// to really remove only the extension ad the end
// It doesnt take care of things like
// file.bmp.bmp.bmp ...
string newFileName = String.Format("{0}_{1}{2}.{3}",
file.FullName.Replace(file.Extension,String.Empty),
(char)(charIndex++ + 97),
(numericIndex > -1 ? String.Format("{0:D4}", numericIndex) : String.Empty),
file.Extension);
// Rename the File
file.MoveTo(newFileName);
// Increment Counters.
if (charIndex > 25)
{
charIndex = 0;
numericIndex++;
}
}
You can try something like this
const string directory = #"C:\\wherever";
string[] fiNames = new string[]{ "abc", "pas", "etc",};
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
int x = 0;
string ending = "";
for(int i = fiNames.Count()-1; i>=0; i--)
{
if(x%26==0)
{
x=0
if( ending=="")
ending="1";
else
ending=(System.Convert.ToInt32(ending)+1).ToString();
}
System.IO.File.Move(directory+fiNames[i], fiNames[i]+alphabet[x].ToString()+ending);
x++;
}

Looking for a tag in a txt doc

Ok I tried all the things that you all sugested, but it is still not working for me. I am not sure why but it will not kick out the output sometimes and sometimes it it puts an out put that is not right. What am I doing wrong.
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("11600");
bool test2 = InPutBox.EndsWith("(");
if (test1 && test2)
{
int first = InPutBox.IndexOf("11600");
int last = InPutBox.LastIndexOf("(");
InPutBox = InPutBox.Substring(first, last - first);
}
}
while (x < 50);
System.Console.WriteLine("'{0}'", line);
if ((line.StartsWith("11600") && line.EndsWith("(")))
{
MessageBox.Show("These are errors in line" + index + ": " + line);
break;
}
}
This:
InPutBox = InPutBox.Substring(last, first - last);
probably needs to be this:
InPutBox = InPutBox.Substring(first, last - first);
May need to add or subtract 1 depending on whether or not you want to include the W or 0. Run it in the debugger to see the actual numbers and you should be able to diagnose more quickly.
Check your conditions. With your current code, .Substring will throw an error if last is not found (because startIndex cannot be less than zero).
You probably want this:
bool test1 = InPutBox.StartsWith("W");
bool test2 = InPutBox.EndsWith("0");
if (test1 && test2) {
int first = InPutBox.IndexOf("W");
int last = InPutBox.LastIndexOf("0");
InPutBox = InPutBox.Substring(last, first - last);
}
#D Stanley is probably right in that the last line is meant to be reversed as well
InPutBox = InPutBox.Substring(first, last - first);
private void InPutBoxMethod()
{
// split text into lines
var lines = textBox1.Text.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
// loop through all lines and check for errors
for (var index = 0; index < lines.Length; index++)
{
var line = lines[index];
System.Console.WriteLine("'{0}'", line);
if ((line.StartsWith("W") && line.EndsWith("0")))
{
MessageBox.Show("These are errors in line " + index + ": " + line);
break;
}
}
}

Finding and replacing text in c#

I need to add functionality in my program so that any file imported it will find the text within the "" of the addTestingPageContentText method as seen below. The two values on each line will then be added to a datagridview which has 2 columns so first text in first column then second in the 2nd column. How would i go about Finding the "sometext" ?
addTestingPageContentText("Sometext", "Sometext");
addTestingPageContentText("Sometext2", "Sometext2");
... continues n number of times.
Neither fast nor efficient, but it's easier to understand for those new to regular expressions:
while (!endOfFile)
{
//get the next line of the file
string line = file.readLine();
EDIT: //Trim WhiteSpaces at start
line = line.Trim();
//check for your string
if (line.StartsWith("addTestingPageContentText"))
{
int start1;
int start2;
//get the first something by finding a "
for (start1 = 0; start1 < line.Length; start1++)
{
if (line.Substring(start1, 1) == '"'.ToString())
{
start1++;
break;
}
}
//get the end of the first something
for (start2 = start1; start2 < line.Length; start2++)
{
if (line.Substring(start2, 1) == '"'.ToString())
{
start2--;
break;
}
}
string sometext1 = line.Substring(start1, start2 - start1);
//get the second something by finding a "
for (start1 = start2 + 2; start1 < line.Length; start1++)
{
if (line.Substring(start1, 1) == '"'.ToString())
{
start1++;
break;
}
}
//get the end of the second something
for (start2 = start1; start2 < line.Length; start2++)
{
if (line.Substring(start2, 1) == '"'.ToString())
{
start2--;
break;
}
}
string sometext2 = line.Substring(start1, start2 - start1);
}
}
However I would seriously recommend going through some of the great tutorials out there on the internet. This is quite a good one
The expression "\"[^"]*\"" would find each...

Categories