Application .net C#
I have problem how to get out (on button click) this (rounded red) value from lista.txt file. In a fact, that's a exchange rate list. Values are changing daily.
Mine is always on the same position.
So far, using line.substring I've got the whole column inline:
5,2599355,3058300,2770031,0057322,4095196,1123050,8419020,7941597,0027418,7470806,9262237,4796281,729514
How do I get just a bold part. Its near end of string (7,479628).
Thanks a lot.
String.Split() should be able to do what you want.
if you already have the column it would be:
var array = column.Split('\t'); //assuming the separator is a tab
In the image it looks like the lines are tab seperated?
You could read each line then perform a split using the tab character....
string[] arsplit = line.Split('\t');
and then grab the item from the array based on index which I presume you'll know
Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"lista.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
int lineCount = 0;
string inputline = "";
do while((inputline = reader.ReadLine()) != null)
{
if(++lineCount == 13)
{
string[] inputArray = inputline.Trim().Split(new char[] {' ','\t'},StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Exchange Rate : '{0}'", inputArray[2]);
break;
}
}
}
}
}
I just received solution that works fine from one guy. His suggestion was to check for EUR which I'm interested for. So, after downloading file, approach is:
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(fullPath);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)//jump first row, it's header don't need it
{
counter++;
continue;
}
if (line.Contains("EUR"))
{
line = line.Replace(" ", "");//clean spaces
line = line.Substring(3 + 3 + 3 + 8, 8);
Response.Write(line);
}
counter++;
}
file.Close();
So it maybe it can be useful for someone. In this moment I don't know which of your solutions is best. Just want to thank to all of you for help me in so short time.
Related
I tried making a script that would read a TXT file line by line, and change labels depending on what is inside.
Is there a way to check which line is being read?
This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class and you can just check the line string and matches with your desire label and replace with that.
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();
OR
using System;
using System.IO;
public class Example
{
public static void Main()
{
string fileName = #"C:\some\path\file.txt";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Hope this will help you.
You can try querying file with a help of Linq:
using System.IO;
using System.Linq;
...
var modifiedLines = File
.ReadLines(#"c:\myInitialScript.txt") // read file line by line
.Select((line, number) => {
//TODO: relevant code here based on line and number
// Demo: return number and then line itself
return $"{number} : {line}";
})
// .ToArray() // uncomment if you want all (modified) lines as an array
;
If you want write modified lines to a file:
File.WriteAllLines(#"c:\MyModifiedScript.txt", modifiedLines);
If you insist on StreamReader, you can implement a for loop:
using (StreamReader reader = new StreamReader("c:\myInitialScript.txt")) {
for ((string line, int number) record = (reader.ReadLine(), 0);
record.line != null;
record = (reader.ReadLine(), ++record.number)) {
//TODO: relevant code here
// record.line - line itself
// record.number - its number (zero based)
}
}
I have a text file contains several lines with words, for example like this
cards
door
lounge
dog
window
I want to add a new word into that list with the condition that it does not already exist in the list. For example I want to add wind or car
I use File.ReadAllText(#"C:\Temp.txt").Contains(word)
But the problem is window contains wind and cards contain car
Is there any way to compare it uniquely?
If you have not a huge file, you can read it to memory and process it like any array:
var lines = File.ReadAllLines(#"C:\Temp.txt");
if(lines.Any(x=>x == word)
{
//There is a word in the file
}
else
{
//Thee is no word in the file
}
Use File.ReadLine() and check for with String.equals(), dont look for substrings. Something Like this:
while(!reader.EndOfFile0
{
if(String.Compare(reader.ReadLine(),inputString, true) == 0)
{
//do your stuf here
}
}
You should do through Regex match so that you are matching an exact work, and I have made this below as case insensitive.
using ConsoleApplication3;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public static class Program
{
private static void Main(string[] args)
{
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\temp\\test.txt");
var line = string.Empty;
string fileData = file.ReadToEnd();
file.Close();
fileData = "newword".InsertSkip(fileData);
StreamWriter fileWrite = new StreamWriter(#"C:\temp\test.txt", false);
fileWrite.Write(fileData);
fileWrite.Flush();
fileWrite.Close();
}
public static string InsertSkip(this string word, string data)
{
var regMatch = #"\b(" + word + #")\b";
Match result = Regex.Match(data, regMatch, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (result == null || result.Length == 0)
{
data += Environment.NewLine + word;
}
return data;
}
}
Although I am reading an entire file and writing an entire file back. You can improve the performance by only writing one word rather a whole file again.
you can do something like
string newWord = "your new word";
string textFile = System.IO.File.ReadAllText("text file full path");
if (!textFile.Contains(newWord))
{
textFile = textFile + newWord;
System.IO.File.WriteAllText("text file full path",textFile);
}
I'm trying to count the number of words from a text file, namely this, to start.
This is a test of the word count program. This is only a test. If your
program works successfully, you should calculate that there are 30
words in this file.
I am using StreamReader to put everything from the file into a string, and then use the .Split method to get the number of individual words, but I keep getting the wrong value when I compile and run the program.
using System;
using System.IO;
class WordCounter
{
static void Main()
{
string inFileName = null;
Console.WriteLine("Enter the name of the file to process:");
inFileName = Console.ReadLine();
StreamReader sr = new StreamReader(inFileName);
int counter = 0;
string delim = " ,.";
string[] fields = null;
string line = null;
while(!sr.EndOfStream)
{
line = sr.ReadLine();
}
fields = line.Split(delim.ToCharArray());
for(int i = 0; i < fields.Length; i++)
{
counter++;
}
sr.Close();
Console.WriteLine("The word count is {0}", counter);
}
}
Try to use regular expression, e.g.:
int count = Regex.Matches(input, #"\b\w+\b").Count;
this should work for you:
using System;
using System.IO;
class WordCounter
{
static void Main()
{
string inFileName = null;
Console.WriteLine("Enter the name of the file to process:");
inFileName = Console.ReadLine();
StreamReader sr = new StreamReader(inFileName);
int counter = 0;
string delim = " ,."; //maybe some more delimiters like ?! and so on
string[] fields = null;
string line = null;
while(!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter+=fields.Length; //and just add how many of them there is
}
sr.Close();
Console.WriteLine("The word count is {0}", counter);
}
}
A couple hints.
What if you just have the sentence "hi" what would be your output?
Your counter calculation is: from 0 through fields.Length, increment counter. How are fields.Length and your counter related?
you're probably getting a one off error, try something like this
counter = 0;
while(!sr.EndOfStream)
{
line = sr.ReadLine();
fields = line.Split(delim.ToCharArray());
counter += field.length();
}
there is no need to iterate over the array to count the elements when you can get the number directly
using System.IO;
using System;
namespace solution
{
class Program
{
static void Main(string[] args)
{
var readFile = File.ReadAllText(#"C:\test\my.txt");
var str = readFile.Split(new char[] { ' ', '\n'}, StringSplitOptions.RemoveEmptyEntries);
System.Console.WriteLine("Number of words: " + str.Length);
}
}
}
//Easy method using Linq to Count number of words in a text file
/// www.techhowdy.com
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FP_WK13
{
static class Util
{
public static IEnumerable<string> GetLines(string yourtextfile)
{
TextReader reader = new StreamReader(yourtextfile);
string result = string.Empty;
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
reader.Close();
}
// Word Count
public static int GetWordCount(string str)
{
int words = 0;
string s = string.Empty;
var lines = GetLines(str);
foreach (var item in lines)
{
s = item.ToString();
words = words + s.Split(' ').Length;
}
return words;
}
}
}
This is the code I've seen so far to delete last 3 lines in a text file, but it's required to determine string[] lines = File.ReadAllLines(); which is nt necessary for me to do so.
string[] lines = File.ReadAllLines(#"C:\\Users.txt");
StringBuilder sb = new StringBuilder();
int count = lines.Length - 3; // except last 3 lines
for (int s = 0; s < count; s++)
{
sb.AppendLine(lines[s]);
}
The code works well, but I don't wanna re-read the file as I've mentioned the streamreader above :
using (StreamReader r = new StreamReader(#"C:\\Users.txt"))
Im new to C#, as far as I know, after using streamreader, and if I wanna modify the lines, I have to use this :
while ((line = r.ReadLine()) != null)
{
#sample codes inside the bracket
line = line.Replace("|", "");
line = line.Replace("MY30", "");
line = line.Replace("E", "");
}
So, is there any way to delete the last 3 lines in the file within the "while ((line = r.ReadLine()) != null)" ??
I have to delete lines, replace lines and a few more modications in one shot, so I can't keep opening/reading the same text file again and again to modify the lines. I hope the way I ask is understable for you guys >.<
Plz help me, I know the question sounds simple but I've searched so many ways to solve it but failed =(
So far, my code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication11
{
public class Read
{
static void Main(string[] args)
{
string tempFile = Path.GetTempFileName();
using (StreamReader r = new StreamReader(#"C:\\Users\SAP Report.txt"))
{
using (StreamWriter sw = new StreamWrite (#"C:\\Users\output2.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
line = line.Replace("|", "");
line = line.Replace("MY30", "");
line = line.Replace("E", "");
line = System.Text.RegularExpressions.Regex.Replace(line, #"\s{2,}", " ");
sw.WriteLine(line);
}
}
}
}
}
}
Now my next task is to delete the last 3 lines in the file after these codes, and I need help on this one.
Thank you.
With File.ReadAllLines you have already read the file, so you can process each one line in the string[] (replaces and regexes), and then write them in the output. You don't have to reread them and put them in the StringBuilder.
You could keep a "rolling window" of the previous three lines:
string[] previousLines = new string[3];
int index = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
if (previousLines[index] != null)
{
sw.WriteLine(previousLines[index]);
}
line = line.Replace("|", "")
.Replace("MY30", "")
.Replace("E", "");
line = Regex.Replace(line, #"\s{2,}", " ");
previousLines[index] = line;
index = (index + 1) % previousLines.Length;
}
Instead of appending the lines directly to the string builder, you could keep a list of the lines and join them later on. That way you can easily leave out the last three lines.
To reduce the amount lines you have to keep in the list, you could regularly append one line of the list and remove it from it. So you would keep a buffer of 3 lines in an array and would pop & append a line whenever the buffer contains 4 lines.
I would really appreciate if somebody could help me/offer advice on this.
I have a file, probably about 50000 lines long, these files are generated on a weekly basis. each line is identical in terms of type of content.
original file:
address^name^notes
but i need to perform a switch. i need to be able to switch (on each and every line) the address with the name. so after the switch has been done, the names will be first, and then addresses and then notes, like so:
result file:
name^address^notes
50,000 isn't that much these days, so simply reading in the whole file and outputting the wanted format should work fine for you:
string[] lines = File.ReadAllLines(fileName);
string newLine = string.Empty;
foreach (string line in lines)
{
string[] items = line.Split(myItemDelimiter);
newLine = string.Format("{0},{1},{2}", items[1], items[0], items[2]);
// Append to new file here...
}
How about this?
StreamWriter sw = new StreamWriter("c:\\output.txt");
StreamReader sr = new StreamReader("c:\\input.txt");
string inputLine = "";
while ((inputLine = sr.ReadLine()) != null)
{
String[] values = null;
values = inputLine.Split('^');
sw.WriteLine("{0}^{1}^{2}", values[1], values[0], values[2]);
}
sr.Close();
sw.Close();
Go go gadget REGEX!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static string Switcheroo(string input)
{
return System.Text.RegularExpressions.Regex.Replace
(input,
#"^([^^]+)\^([^^]+)\^(.+)$",
"$2^$1^$3",
System.Text.RegularExpressions.RegexOptions.Multiline);
}
static void Main(string[] args)
{
string input = "address 1^name 1^notes1\n" +
"another address^another name^more notes\n" +
"last address^last name^last set of notes";
string output = Switcheroo(input);
Console.WriteLine(output);
Console.ReadKey(true);
}
}
}