How to remove texts after a character? - c#

I have an array that holds user and passwords in user:pass form, and I like ro remove lines which pass is less than 8 characters or password uses repetitive chars like 111111,22222222222,...
I have tried string.take but it takes lines completely, I need conditional deletion.
public string[] lines;
//open file dialogue to load the user pass file
lines = File.ReadAllLines(openFileDialog1.FileName);
//delete button click event
//the place that I have problem
I have email:pass combination like so:
email1:1234567895121
email2:12345
email4:11111
email5"454545454545
and I would like the output to be like
email1:1234567895121
email5"454545454545

Just loop the characters of every line and see if the current is equal to the previous:
public string[] lines = File.ReadAllLines(openFileDialog1.FileName);
var filteredLines = new List<string>(lines);
foreach(var line in lines)
{
var pair = line.Split(':');
var mail = pair[0];
var pass = pair[1]; // may throw exception on invalid format of your line
for(int i = 1; i < pass.Length; i++)
{
if(pass[i] == pass[i - 1])
{
filteredLines.Remove(line);
break; // will break inner loop and continue on next line
}
}
}

string[] lines =
{
"email1:1234567895121",
"email2:12345",
"email3:22222222222",
"email4:11111",
"email5:454545454545"
};
lines = lines
.Where(s =>
{
string pass = s.Split(new[] { ':' }, 2)[1];
return pass.Length >= 8 && pass.Any(c => c != pass[0]);
})
.ToArray();
foreach (var s in lines)
Console.WriteLine(s);
Output:
email1:1234567895121
email5:454545454545

Related

Append string in a specific place of a text file

I have hundreds of files in a directory. Many of the text files have the Code Column values as blank and i need to iterate over all the text files and fill it. I am able to write the code to add the code value in a new line, but i am not able to write it under code column. String value is: "STRINGTOENTER". I only want it be entered in the 1st line after the header. The last line should be left alone
Id Code File_Number Suffix Check_Number Check_Date
047 7699 01 99999 11/11/2012
1 -6.15
Below is my code snippets that add the value at a newline. I think I need to do a regular expression or a tab delimited type solution here.
public static void AddAStringtoAllTextFiles()
{
try
{
string path = #"C:\Users\ur\Desktop\TestFiles\";
string[] fileEntries = Directory.GetFiles(path);
for (int i = 0; i < fileEntries.Length; i++)
{
File.AppendAllText(fileEntries[i], "STRINGTOENTER" + Environment.NewLine);
}
}
catch (Exception e)
{
throw e;
}
}
EDITED
please try this with the assumption that its space(s) delimited.
its working on my VS2017 and kindly add the using statement on the top as below .
using System.Text.RegularExpressions
public static void AddAStringtoAllTextFiles()
{
try
{
string path = #"C:\Users\ur\Desktop\TestFiles\";
var fileEntries = Directory.GetFiles(path);
int indexPosition2InsertData=1;
foreach (var entry in fileEntries)
{
var lines = File.ReadAllLines(entry);
for (var index = 1; index < lines.Length; index++) //starting from first row, leaving the header
{
var split= Regex.Split(lines[index].Trim(), #"\s{1,}"); //reading the line with space(s)
if(split.Length==5) //edited //checking if the row is not blank
{
var list = split.ToList(); //convert to list to insert
list.Insert(indexPosition2InsertData, "STRINGTOENTER"); //inserting at the index 1
lines[index] = string.Join("\t", list);
}
}
File.WriteAllLines(entry, lines);
}
}
catch (Exception e)
{
throw e;
}
}
I am getting this after running the code.
Id Code File_Number Suffix Check_Number Check_Date
047 STRINGTOENTER 7699 01 99999 11/11/2012
1 -6.15
Please let me know if this helps.
Assuming each file has the right tab delimitation (and that's a big assumption given the question quality)
// Get the files
var fileEntries = Directory.GetFiles(path);
// iterate through each file name
foreach (var entry in fileEntries)
{
// Load the File into the lines array
var lines = File.ReadAllLines(entry);
// Iterate over each line
if(lines.Length >1)
{
// Split the lines by tab
var split = lines[1].Split('\t');
// your code should be at array index 1
split[1] = "STRINGTOENTER";
// write the whole line back
lines[1] = string.Join("\t", split);
// write the file
File.WriteAllLines(entry, lines);
}
}
Note : you should probably do this with a CSV parser, this was only for academic purposes and totally untested
I want to show my desired solution based on your input. Amazing how a simple piece of code can contribute to solving a larger and a complex problem. Thanks again!
public static void AddClientCodetoAllTextFiles(string update_batch_with_clientcode, string batchfilepathtobeupdated)
{
try
{
var fileEntries = Directory.GetFiles(#batchfilepathtobeupdated.Trim());
foreach (var entry in fileEntries)
{
var lines = File.ReadAllLines(entry);
if (lines.Length > 1)
{
for (int i = 1; i < lines.Length - 1; i++)
{
var split = lines[i].Split('\t');
split[1] = update_batch_with_clientcode.Trim();
lines[i] = string.Join("\t", split);
File.WriteAllLines(entry, lines);
}
}
}
}
catch (Exception e)
{
throw e;
}
}

Change a text in files in a folder next to string "Text_ID"

  Example of a text file below 
text_file a
Text_ID "441124_aad0656_1234"
Text_FILE_NAME
I would like to keep only last index of string "1234"
StreamReader streamReader = new StreamReader(text);
string text2;
while ((text2 = streamReader.ReadLine()) != null)
{
num++;
string[] array3 = text2.Split(new char[0]);
if (array3[0] == "Text_ID")
{
string[] array4 = array3[1].Split(new char[] {'_'});
string value = "Text_ID" + " " + '"' + array4[1];
streamWriter.WriteLine(value);
}
else
{
streamWriter.WriteLine(text2);
}
}
try below code, and hope it should work for you.
var startsWith = "Text_ID";
var allLines = File.ReadAllLines("a.txt").ToList();
allLines = allLines.Select(ln =>
{
if(ln.StartsWith(startsWith))
{
var finalValue = ln.Split(' ')[1].Trim('"').Split('_').Last();
//get update line
return string.Format("{0} \"{1}\"", startsWith, finalValue);
}
return ln;
}).ToList();
//Write back to file.
File.WriteAllLines("a.txt", allLines.ToArray());
Content before code execution.
Record 1
Text_ID "441124_aad0656_1234"
other content.
Record 2
Text_ID "Deepak_Sharma"
other content for line 2
Content in file after execution.
Record 1
Text_ID "1234"
other content.
Record 2
Text_ID "Sharma"
other content for line 2
You could use File.ReadAllLines to read the file into an array, then search through the array for the line you want to change, replace that line with the new string, and then use File.WriteAllLines to write the array back to the file:
var filePath = #"f:\public\temp\temp.txt";
// The string to search for
var searchTxt = "Text_ID";
// Read all the lines of the file into an array
var fileLines = File.ReadAllLines(filePath);
// Loop through each line in the array
for(int i = 0; i < fileLines.Length; i++)
{
// Check if the line begins with our search term
if (fileLines[i].Trim().StartsWith(searchTxt, StringComparison.OrdinalIgnoreCase))
{
// Get the end of the line, after the last underscore
var lastPartOfLine = fileLines[i].Substring(fileLines[i].LastIndexOf("_") + 1);
// Combine our search string, a quote, and the end of the line
fileLines[i] = $"{searchTxt} \"{lastPartOfLine}";
// We found what we were looking for, so we can exit the for loop now
// Remove this line if you expect to find more than one match
break;
}
}
// Write the lines back to the file
File.WriteAllLines(filePath, fileLines);
If you only want to save the last four lines of the file, you can call Skip and pass in the Length of the array minus the number of lines you want to keep. This skips all the entries up to the number that you want to save:
// Read all the lines of the file into an array
var fileLines = File.ReadAllLines(filePath);
// Take only the last 4 lines
fileLines = fileLines.Skip(fileLines.Length - 4).ToArray();

Returning values from text file : C#

I have a .txt file that contains information about vehicles that I add via another project. I want to read the text file, retrieve each VIN number, and place just the actual number itself in a combo box when the form is loaded.
The info for each vehicle in the txt file looks like:
Model: 'model'
Manufacturer: 'manufacturer'
VIN Number: 'VIN number'
This is what I have:
using (StreamReader reader = new StreamReader(#"D:\carCenter\carCenter\bin\Debug\Vehicles.txt"))
{
string[] lines = File.ReadAllLines(#"D:\carCenter\carCenter\bin\Debug\Vehicles.txt");
foreach(string line in lines)
{
if (line.Contains("VIN"))
{
Char colon = ':';
string[] vins = line.Split(new string[] {"VIN Number: "}, StringSplitOptions.None);
for (int i = 0; i < 1; i++)
{
foreach(var vin in vins)
{
vinComboBox.Items.Add(vins[i]);
}
}
}
}
One solution is to have a general purpose function like this:
private String GetDataToRightOfLastColon(String line)
{
line = line.Trim();
var indexOfLastColon = line.LastIndexOf(':');
/* If line does not contain a ':' character,
or ':' is the last non-space character in line,
throw an exception. */
if ((indexOfLastColon == -1) || (indexOfLastColon == (line.Length - 1)))
throw new ArgumentException(
String.Format("The line '{0}' does not have the correct format.", line));
return line.Substring(indexOfLastColon + 1).Trim();
}
Next, apply that function via LINQ to process the text file and populate the combobox:
vinComboBox.Items.AddRange(
File
.ReadAllLines(#"D:\carCenter\carCenter\bin\Debug\Vehicles.txt")
.Where(line => line.Trim().StartsWith("VIN"))
.Select(line => GetDataToRightOfLastColon(line))
.ToArray()
);

Pick a specific line from a text file and spilt the line in an array

What I would like to do is pick a line from a text file. That line number is corresponding with a local variable. So if the variable is 1, pick line one. The text file is in Resources and called nl_5.txt. After that the picked line (a word) should placed in a new array, but each letter should be placed at a new index. So if the variable is 1, line one is apple. Something like this:
string[] arr1 = new string[] { "a", "p", "p", "l", "e" }; (0=a 1=p 2=p 3=l 4=e)
If the local variable is changing to 2, line two should be read and the array should be changed with the other line (other word, other letters). How should I do this?
I found different variants like read the complete file or read specific lines who're defined, but I've tried a lot with no correct result.
int lineCount = File.ReadAllLines(#"C:\test.txt").Length;
int count = 0;
private void button1_Click(object sender, EventArgs e)
{
var reader = File.OpenText(#"C:\test.txt");
if (lineCount > count)
{
textBox1.Text = reader.ReadLine();
count++;
}
}
First, let's obtain the word via Linq:
int line = 3; // one based line number
string word = File
.ReadLines(#"C:\test.txt") //TODO: put actual file name here
.Skip(line - 1) // zero based line number
.FirstOrDefault();
Then convert word into the array
string[] arr1 = word
.Select(c => c.ToString())
.ToArray();
If you have to read the file for many different line you can cache the file:
// Simplest, not thread safe
private static string[] file;
// line is one-based
private static string[] getMyArray(int line) {
if (null == file)
file = File.ReadAllLines(#"C:\test.txt");
// In case you have data in resource as string
// read it and (split) from the resource
// if (null == file)
// file = Resources.MyString.Split(
// new String[] { Environment.NewLine }, StringSplitOptions.None);
string word = (line >= 1 && line < file.Length - 1) ? file[line - 1] : null;
if (null == word)
return null; // or throw an exception
return word
.Select(c => c.ToString())
.ToArray();
}

How to get delimiter count as a input? [duplicate]

This question already has answers here:
Split a string with delimiters but keep the delimiters in the result in C#
(17 answers)
Closed 8 years ago.
in the program, i have to handle a input table like this.
a:1
b:2
c:3
?:6
#:14
obviously, delimiter is ":" and "\n"
however, input like this will catch an exception
::2
I want to make ':' store into a char list as well.
how do i modify these code?
and where should I put try-catch in?
String[] str;
str = textbox.Text.Trim().Split(':', '\n');
for (i = 0; i < str.Length; i = i + 2){
char tempC;
float tempFreq;
if (char.TryParse(str[i], out tempC))
c.Add(tempC);
if (float.TryParse(str[i + 1], out tempFreq))
freq.Add(tempFreq);
}
First you need to parse your text line by line.Use the Lines property for that
Then you can just check if the current line starts with :
var lines = textbox.Lines;
foreach(var line in lines)
{
if(line.StartsWith(':'))
{
c.Add(':');
float tempFreq;
if (float.TryParse(line.Split(':').Last(), out tempFreq))
freq.Add(tempFreq);
}
else
{
char tempC;
float tempFreq;
string[] parts = line.Split(':');
if (char.TryParse(parts[0], out tempC))
c.Add(tempC);
if (float.TryParse(parts[1], out tempFreq))
freq.Add(tempFreq);
}
}
Btw, I assumed it is WinForms, Lines property might not exist in WPF, if that is the case just split the text by newline character first, then iterate over the lines and do the same things.
You can use String.Split with StringSplitOptions.RemoveEmptyEntries, you can also split the lines first.
Your sample data with edge cases
var text = #"a:1
b:2
c:3
?:6
::2
#:14 ";
LINQ query which selects the char and the float as pair:
float freq = 0;
string[] lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var lineTokens = lines.Select(l => l.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries))
.Where(arr => arr.Length == 2 && arr[0].Trim().Length == 1 && float.TryParse(arr[1].Trim(), out freq))
.Select(arr => new { chr = arr[0].Trim()[0], freq });
Output:
foreach(var x in lineTokens)
Console.WriteLine("Char:{0} Frequency:{1}", x.chr, x.freq);
Char:a Frequency:1
Char:b Frequency:2
Char:c Frequency:3
Char:? Frequency:6
Char:# Frequency:14

Categories