Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a text file that the user upload to the application through OpenFileDialog then when the file open the program is reading it line by line using:
string[] data = File.ReadAllLines(file);
how do i make a dynamic editing for each line so that after the Nth number or letter put a space then display the result to the user without writing over the file,
for example:
if my file contain:
0000000000BADBAD
2323040007BADAAD
4234420087BADBAC
the Display should be
0000000000 BADBAD
2323040007 BADAAD
4234420087 BADBAC
Once you have read all the lines into string array, data is isolated from your file i.e. any modification in data won't be reflected into your file. You can manipulate it like any other object.
One of the way manipulating data and achieving your result would be:
foreach (string value in data)
{
Console.WriteLine(value.Insert(10, " "));
}
You can loop throught your lines and extract the data with Regex, example:
string str = "0000000000BADBAD";
var match = Regex.Match(str, #"(?<Number>\d+)(?<Text>.*)");
var number = match.Groups["Number"].Value;
var text = match.Groups["Text"].Value;
string result = String.Format("{0} {1}", number, text);
And write result on your output.
Another alternative is using Linq
string str = "0000000000BADBAD";
int n;
string number = String.Join("", str.TakeWhile(c => int.TryParse(c.ToString(), out n)));
string text = String.Join("", str.SkipWhile(c => int.TryParse(c.ToString(), out n)));
string result = String.Format("{0} {1}", number, text);
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need to ignore reading the particular line while reading the whole document.
for example, I have chunk of data and I have read it using File.ReadAllText(filePath); and I need to ignore reading a particular line, Say 50 and need to read the other lines. So far I have the below code.
string fileName = "TextFile.config";
string filePath = Path.GetDirectoryName("TextFile.config") + fileName;
string text = File.ReadAllText(filePath);
You can use ReadLines and Where like here:
int[] ignoreLines = { 50 };
IEnumerable<string> relevantLines = File.ReadLines(filePath)
.Where((line, index) => !ignoreLines.Contains(index + 1));
string resultString = string.Join(Environment.NewLine, relevantLines);
Use File.ReadAllLines, this will give you all lines of the file in an array, you can then loop through this array to check for the line you want to ignore (or not ignore), (either with an index or with string.StartsWith / string.EndsWith
File.ReadLines Method (String)
Reads the lines of a file.
List.RemoveAt Method (Int32)
Removes the element at the specified index of the List.
List.RemoveRange Method (Int32, Int32)
Removes a range of elements from the List.
Exmaple
string fileName = "TextFile.config";
string filePath = Path.GetDirectoryName("TextFile.config") + fileName;
var lines = File.ReadLines(filePath).ToList();
lines.RemoveAt(49) // Remove 50th line
// or
lines.RemoveRange(49,10) // Remove 50th line + 9 more
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I guys im trying to workout C# code to extract the first two words from string. below is code im doing.
public static string GetDetailsAsString(string Details)
{
string Items = //how to get first 2 word from string???
if (Items == null || Items.Length == 0)
return string.Empty;
else
return Items;
}
Define "words", if you want to get the first two words that are separated by white-spaces you can use String.Split and Enumerable.Take:
string[] words = Details.Split();
var twoWords = words.Take(2);
If you want them as separate string:
string firstWords = twoWords.First();
string secondWord = twoWords.Last();
If you want the first two words as single string you can use String.Join:
string twoWordsTogether = string.Join(" ", twoWords);
Note that this simple approach will replace new-line/tab characters with empty spaces.
Assuming the words are separated by whitespaces:
var WordsArray=Details.Split();
string Items = WordsArray[0] + ' ' + WordsArray[1];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What i'm trying to do is delete certain text from a .text file. For example:
I have a .text file with the following text.
Hello
This
Is <----- I would like to delete this line from the file.
My
Text
I have tried to use the following code:
private void DeleteButton2_Click(object sender, EventArgs e)
{
if (comboBox2.SelectedItem == "")
{
MessageBox.Show("Please Select a Contact.");
}
else
{
comboBox2.Items.Remove(comboBox2.SelectedItem);
comboBox1.Items.Remove(comboBox2.SelectedItem);
File.Delete(comboBox2.SelectedItem + ".txt");
string SelectedItem = comboBox2.SelectedItem.ToString();
string empty = "";
string Readcurrentcontacts = File.ReadAllText(contactpath);
Readcurrentcontacts.Replace(SelectedItem, empty);
}
}
With no succesful results. If you need any further information please let me know! Thank you in advance!
The File.ReadLines and File.WriteAllLines methods would be useful here:
string SelectedItem = comboBox2.SelectedItem.ToString();
var allLines = File.ReadLines(contactpath)
// Linq filter to exclude selected item
var newLines = allLines.Where(line => line != SelectedItem);
File.WriteAllLines(contactpath, newLines);
Note that Where is a Linq extension method that takes an IEnumerable as input, and returns a subset based on the predicate that you provide. So, the line above takes the input (all lines in the file), and returns all lines that are not equal to SelectedItem.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am looking for code to open a text file , then read the text file line by line , if the line in the text file (each line will store approx 5 values) does not contain a certain value e.g "hart" then I wand to remove that line. I am using c# and vs2012 , could anyone show me how to do this ? the file being read from is a csv file. I have no code example here as my current code does not work and I feel givin example will only cause more confusion than asking for someone to show me a clean fresh approach to doing this.
I have added the code I currently have which adds all of the data to a text file however the code I need to figure out is to take these results and filter them
foreach (DataRow dr in this.CalcDataSet.Items)
{
foreach (object field in dr.ItemArray)
{
str.Append(field.ToString() + ",");
}
str.Replace(",", "\n", str.Length - 1, 1);
}
try
{
System.IO.File.WriteAllText(Filepath, str.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Write Error :" + ex.Message);
}
var lines = System.IO.File.ReadAllLines(Filepath).ToList();
var acceptedLines = new List<string>();
foreach (var line in lines)
if (Matches(line))
acceptedLines.Add(line);
System.IO.File.WriteAllLines(Filepath, acceptedLines);
}
private bool Matches(string s)
{
if (s == cmbClientList.SelectedText.ToString())
{
return true;
}
else return false;
}
Use the TextFieldParser class to open and read the file, and split the values into an array. You can then examine each item on each line to see if it contains the value you want.
If the line contains the value, then write the line to a new file. If it doesn't contain the value, then do not write to the new file.
When you're done, close the input and output files. Then delete the original input file and rename the output file.
You can't easily read and modify a text file in-place.
Another option would be to read using TextFieldParser and write to an in-memory stream. At the end, write from the memory stream back to the original file. This will work if the file is small enough to fit in memory.
This will basically do what you want:
var lines = System.IO.File.ReadAllLines("somefile.csv");
var acceptedLines = new List<string>();
foreach (var line in lines)
if (Matches(line))
acceptedLines.Add(line);
System.IO.File.WriteAllLines("output.csv", acceptedLines);
private bool Matches(string s) {
// Whatever you want, return true to include the line, false to exclude)
}
you can do this
string[] lines = File.ReadAllLines("yourfile.csv");
List<string> linesToWrite = new List<string>();
int currentCount = 0;
foreach(string s in lines)
{
if(s.Contains("YourKeyValue"))
linesToWrite.Add(s);
}
File.WriteAllLines("yourfile.csv", linesToWrite );
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
string text = "try your {{equal|even out|regularize} out|steady|tied|equal}";
Actually I want to split all words within the outer brackets ({}).
For example, if this is the string: "{{equal|even out|regularize} out|steady|tied|equal}", I want the split result array to be this:
{ equal,
even out,
regularize,
out,
steady,
tied,
equal }
string text = "try your {{equal|even out|regularize} out|steady|tied|equal} {champion|finest|top-quality}";
string1 = "try";
string2 = "your";
string3="{{equal|even out|regularize} out|steady|tied|equal}";
string4="{champion|finest|top-quality}";
How to split like this... please help me... Thanks !
try this :
string text = "try your {{equal|even out|regularize} out|steady|tied|equal}";
text = text.Remove(0, text.IndexOf('{'));
var array = text.Split('{', '}', '|');
array.ToList().ForEach(item =>
{
Console.WriteLine(item);
});
output :
equal
even out
regularize
out
steady
tied
equal