Im trying to edit a file that is on danish, with ÆØÅ letters.
But i'm doing somthing wrong, i can ad a line with the correct letters, but it seams like im not reading the excisting lines correct, and therefore I get "2. P�skedag" insted of "2. Påskedag"
My code is
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string filePath = #"C:\Users\tib5ka\Desktop\FællesVagtplan-filer\sheet001.htm";
string[] lines = File.ReadAllLines(filePath, Encoding.UTF8);
for (int i = 0; i < lines.Length; i++)
{
// lines[i] = lines[i].Replace("INFOBAR :", "<marquee>Det er froååkosttid.</marquee>");
}
File.WriteAllLines(filePath, lines, Encoding.UTF8);
}
}
after hours of search I'd finaly found the solution just as a posted my question in here.
It was my encoding in the read line that was wrong.
It shoud be System.Text.Encoding.Default
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string filePath = #"C:\Users\tib5ka\Desktop\FællesVagtplan-filer\sheet001.htm";
string[] lines = File.ReadAllLines(filePath, System.Text.Encoding.Default);
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Replace("INFOBAR :", "<marquee>Det er froååkosttid.</marquee>");
}
File.WriteAllLines(filePath, lines, Encoding.UTF8);
}
}
Related
How to append text (from txt file e.g englishWord.txt) to the end of all lines (from another txt file e.g PolishWord.Txt) ?
i have one txt file with many english word and translated polish word in another txt file. I would like the result to be such as it:
englishWord.txt:
familiar
involve
ability
expand
polishWord.txt:
znajomy
angażować
umiejętność
rozszerzać
Program make the result.txt like this:
familiar - znajomy
involve - angazować
ability - umiejętność
expand - rozszerzac
Thanks for your attention. I’m looking forward to your reply.
Sorry for my bad English.
This is what i tried:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
string englishWord = File.ReadAllText("c:/temp/english.txt");
string polishWord = File.ReadAllText("c:/temp/polish.txt");
foreach (var lineE in englishWord)
{
string lineEnglish = lineE;
}
foreach (var lineP in polishWord)
{
string linePolish = lineP;
}
string result = lineEnglish + " - " + linePolish;
result = File.WriteAllText"c:/temp/result.txt";
}
}
}
An easy way to do this would be to first read the line from both files, split those lines by spaces into two arrays, then iterate through those arrays at the same time. I.E.:
System.IO.StreamReader english = new System.IO.StreamReader("englishWord.txt");
System.IO.StreamReader polish = new System.IO.StreamReader("polishWord.txt");
String englishLine = english.ReadLine();
String polishLine = polish.ReadLine();
String englishWords[] = englishLine.split(' ');
String polishWords[] = polishLine.split(' ');
for (int i = 0; i < englishWords.Length; i++) {
/* Output englishWords[i] and polishWords[i] to result.txt here */
}
Hope this helps!
Try this:
using (var english = new StreamReader("englishWord.txt"))
using (var polish = new StreamReader("polishWord.txt"))
using (var result = new StreamWriter("result.txt"))
{
while (!english.EndOfStream && !polish.EndOfStream)
{
result.Write(english.ReadLine());
result.Write(" - ");
result.Write(polish.ReadLine());
result.WriteLine();
}
}
This produces results exactly like in the specification. However, if you're trying to build something like a dictionary I'd suggest other formats like writing to Excel file or a csv file.
//load files
var englishFile = File.OpenText("englishWord.txt").ReadToEnd();
var polishFile = File.OpenText("polishWord.txt").ReadToEnd();
//convert to string arrays
var englishArray = englishFile.Split(' ');
var polishArray = polishFile.Split(' ');
//build output string
String outputString = "";
//take the lenght of the shorter array in case they're not the same length
int maxLength = Math.Min(englishArray.Length, polishArray.Length);
for (int i=0; i<maxLength; i++)
{
outputString += englishArray[i] + " - " + polishArray[i] + " ";
}
//write output to file
File.WriteAllText("results.txt", outputString);
I have a homework assignment to create a C# console program. It should create a text file with 2 phrases:
Hello, World!
Goodbye, Cruel World!
Then I also must create a program to read the 2 phrases from the file.
After two hours this is what I have. It works, but I want to rewrite the program to be more efficient. I am mainly struggling on how to output the file into a .cs file capable of running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//structure.txt contains the program we will enter our values into.
String filePath = "Structure.txt";
WriteToFile(filePath);
}
public static void WriteToFile(string filePath)
{
//create a string array to gather our text file information.
StreamReader reader = new StreamReader(filePath);
StreamReader info = new StreamReader("Structure.txt");
StreamWriter writer = new StreamWriter("Hello.cs", true);
String temp = String.Empty;
while (!info.EndOfStream)
{
String tempstring = String.Empty;
tempstring = reader.ReadLine();
while (!reader.EndOfStream)
{
temp = reader.ReadLine();
writer.WriteLine(temp);
if (temp == "//break")
{
writer.WriteLine("String1 = {}", tempstring);
}
}
}
reader.Close();
info.Close();
writer.Close();
}
}
}
More efficient? sure
// write
string[] lines = new [] {"Hello, World!", "Goodbye, Cruel World!"};
File.WriteAllLines("c:\\myFile.txt", lines);
// read
string[] lines = File.ReadAllLines("c:\\myFile.txt");
This is all. . .
this is my code and I also have a snippet in the link below of what my program looks like when run. My problem is with the second text box and that it is filling out with random gibberish. My first text box is working perfectly it is picking a random first name from my text file and putting it into the text box. I dont understand what my second text file isnt doing the same'?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
Random r = new Random();
int currentLinefirst = 1;
string pick = null;
foreach (string line in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\First Names.txt"))
{
if (r.Next(currentLinefirst) == 0)
{
pick = line;
}
++currentLinefirst;
}
textBox1.Text = pick;
}
Random n = new Random();
int currentLinelast = 1;
string pick2 = null;
foreach (string line1 in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\Last Names.txt"))
{
if (n.Next(currentLinelast) == 0)
{
pick2 = line1;
}
++currentLinelast;
}
textBox2.Text = pick2;
}
}
}
i am getting this output of random numbers in textbox
It is probably because your second file contains a line with multiple names. When you call File.ReadLines, it will return an array of string on each line
Try separating you last names with line feeds.
To save the text to a text file use
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Admin\Desktop\test.txt", true))
{
file.WriteLine("First Name: {0} Last Name: {1}", textBox1.Text, textBox2.Text);
}
{0} and {1} are placeholders
if the file is does not exist it will create a new file to the given path and if the file already exists then it will add new entry to the file.
You can try this:
string firstname = textBox1.Text;
string lastname = textBox2.Text;
Byte[] info = new UTF8Encoding(true).GetBytes(firstname + lastname);
string FilePath = yourpath + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt";
using (FileStream fs = File.Create(FilePath))
{fs.Write(info, 0, info.Length);}
I'm trying to read an csv file with the format:
name, location
Joseph, "street xpto, London"
When I read CSV, I split the file to ",", but when the line has "street xpto, London" (other commas) it doesn't work.
Is there some solution to that? I need to do split ignoring commas when find an " ".
var reader = new StreamReader(File.OpenRead(#"C:\example_File.csv"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
String[] values = line.Split(',');
for (int i = 0; i < values.Length; i++)
{
}
}
Don't reinvent the wheel. There are extremely good libraries that will help you do all this. The one I like is CsvHelper available through nuget
Install-Package CsvHelper
or from the project home page.
Text field parser handles this already
using System;
using Microsoft.VisualBasic.FileIO;
class Program
{
static void Main()
{
using (TextFieldParser parser = new TextFieldParser("C:\\csv.txt"))
{
parser.Delimiters = new string[] { "," };
while (true)
{
string[] parts = parser.ReadFields();
if (parts == null)
{
break;
}
Console.WriteLine("{0} field(s)", parts.Length);
}
}
}
}
So I'm working on a little side project in c# and want to read a long text file and when it encounters the line "X-Originating-IP: [192.168.1.1]" I would like to grab the IP and display to console just the recognized IP #, so just 192.168.1.1 etc. I am having trouble understanding regex. Anyone who could get me started is much appreciated. What I have so far is below.
namespace x.Originating.Ip
{
class Program
{
static void Main(string[] args)
{
int counter = 0;
string line;
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\example.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("X-Originating-IP: "))
Console.WriteLine(line);
counter++;
}
file.Close();
Console.ReadLine();
}
}
}
Try this example:
//Add this namespace
using System.Text.RegularExpressions;
String input = #"X-Originating-IP: [192.168.1.1]";
Regex IPAd = new Regex(#"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
MatchCollection MatchResult = IPAd.Matches(input);
Console.WriteLine(MatchResult[0]);
You don't need to use regular expression:
if (line.Contains("X-Originating-IP: ")) {
string ip = line.Split(':')[1].Trim(new char[] {'[', ']', ' '});
Console.WriteLine(ip);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Net.WebClient webclient = new System.Net.WebClient();
string ip = webclient.DownloadString("http://whatismyip.org/");
Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
if (reg.Match(ip).Success)
{
Console.WriteLine(reg.Match(ip).ToString ());
Console.WriteLine("Success");
}
// Console.Write (ip);
Console.ReadLine();
}
}
}
I'm not sure but I suppose your text file contains one IP address each row, now your codes can be simplified like this below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace x.Originating.Ip
{
class Program
{
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines("Your path & filename.extension");
Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
for (int i = 0; i < lines.Length; ++i)
{
if (reg.Match(lines[i]).Success)
{
//Do what you want........
}
}
}
}
}
The following regular expression should get you what you want:
(?<=X-Originating-IP: +)((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)
This uses a positive lookbehind to assert that "X-Originating-IP: " exists followed by an IPv4 address. Only the IP address will be captured by the match.
Rather than doing a regex, it looks like you are parsing a MIME email, consider LumiSoft.Net.MIME which lets you access the headers with a defined API.
Alternatively, use the built in IPAddress.Parse class, which supports both IPv4 and IPv6:
const string x_orig_ip = "X-Originating-IP:";
string header = "X-Originating-IP: [10.24.36.17]";
header = header.Trim();
if (header.StartsWith(x_orig_ip, StringComparison.OrdinalIgnoreCase))
{
string sIpAddress = header.Substring(x_orig_ip.Length, header.Length - x_orig_ip.Length)
.Trim(new char[] { ' ', '\t', '[', ']' });
var ipAddress = System.Net.IPAddress.Parse(sIpAddress);
// do something with IP address.
return ipAddress.ToString();
}