If it is possible to read from a source file, like this:
string fileContent = Resources.Users;
using (var reader = new StringReader(fileContent))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] split = line.Split('|');
string name = split[0];
string last = split[1];
}
}
Then how can you write to the same file?
You can make use of the ResourceWriter .
I'd also suggest that you make use of the ResourceManager to read from the file.
Code from the link source:
using System;
using System.Resources;
public class WriteResources {
public static void Main(string[] args) {
// Creates a resource writer.
IResourceWriter writer = new ResourceWriter("myResources.resources");
// Adds resources to the resource writer.
writer.AddResource("String 1", "First String");
writer.AddResource("String 2", "Second String");
writer.AddResource("String 3", "Third String");
// Writes the resources to the file or stream, and closes it.
writer.Close();
}
}
try this
class Test {
public static void Main() {
ResourceWriter rw = new ResourceWriter("English.resources");
rw.AddResource("Name", "Test");
rw.AddResource("Ver", 1.0 );
rw.AddResource("Author", "www.java2s.com");
rw.Generate();
rw.Close();
}
}
string path = #"c:\temp\contentfilelocation.extension"; //path to resource file location
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter writer = File.CreateText(path))
{
string line = "<name>" + "|" + "<last>";
writer.WriteLine();
}
}
using System;
using System.Resources;
using (ResXResourceWriter resx = new ResXResourceWriter(#"D:\project\files\resourcefile.resx"))
{
resx.AddResource("Key1", "Value");
resx.AddResource("Key2", "Value");
resx.AddResource("Key3", "Value");
resx.Close();
}
Related
So I have this code:
class Program
{
static void Main(string[] args)
{
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var dir = new DirectoryInfo(mydocpath + #"\sample\");
string msg = "Created by: Johny";
foreach (var file in dir.EnumerateFiles("*.txt"))
{
file.AppendText(msg); //getting error here
}
}
}
And I want to add a footer to all the text file in the sample folder, but I'm getting an error because the AppendText is not accepting a string argument. I was just wondering how do I do this?
You want to use the streamwriter from AppendText I think:
static void Main(string[] args)
{
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var dir = new DirectoryInfo(mydocpath + #"\sample\");
string msg = "Created by: Johny";
foreach (var file in dir.EnumerateFiles("*.txt"))
{
var streamWriter = file.AppendText();
streamWriter.Write(msg);
streamWriter.Close();
}
}
FileInfo.AppendText() creates a StreamWriter, it doesn't append text per se. You want to do this:
using (var sw = file.AppendText()) {
sw.Write(msg);
}
AppendText is the extension method for the StreamWriter, see the documentation
So you should write these code instead:
foreach (var file in dir.EnumerateFiles("*.txt"))
{
using (StreamWriter sw = File.AppendText(file.FullName))
{
sw.WriteLine(msg);
}
}
I have a config file called one_two.config.txt containing the path of a log file to be written.
I want to read this line ( 'comdir=C:\Users\One\Desktop' ) and then create a new log file in a given directory.
The log file is going to have some data ( Time / Date / ID etc. )
Here is what i have right now :
string VarSomeData = ""; // Contains Data that should be written in log.txt
for (Int32 i = 0; i < VarDataCount; i++)
{
csp2.DataPacket aPacket;
VarData = csp2.GetPacket(out aPacket, i, nComPort);
VarSomeData = String.Format("\"{0:ddMMyyyy}\",\"{0:HHmmss}\",\"{1}\",\"{2}\",\"{3}\" \r\n", aPacket.dtTimestamp, VarPersNr, aPacket.strBarData, VarId.TrimStart('0'));
string line = "";
using (StreamReader sr = new StreamReader("one_two.config.txt"))
using (StreamWriter sw = new StreamWriter("log.txt"))
{
while ((line = sr.ReadLine()) != null)
{
if((line.StartsWith("comdir="))
{
// This is wrong , how should i write it ?
sw.WriteLine(VarSomeData);
}
}
}
}
Right now the log file is being created in same directory as the config file.
This should get you started:
string line;
using (StreamReader file = new StreamReader("one_two.config.txt"))
using (StreamWriter newfile = new StreamWriter("log.txt"))
{
while ((line = file.ReadLine()) != null)
{
newfile.WriteLine(line);
}
}
So basically, you have a config file containing the path of a log file to write; but you're not saying anything about the content of that log file. You just want to know where to create it, correct?
Something like
string ConfigPath = "one_two.config.txt";
string LogPath = File.ReadAllLines(ConfigPath).Where(l => l.StartsWith("comdir=")).FirstOrDefault()
if (!String.IsNullOrEmpty(LogPath)) {
using (TextWriter writer = File.CreateText(LogPath.SubString(7))) {
writer.WriteLine("Log file created.");
}
}
You can also read the configuration line this way with a little bit more code but you'll get better performance
string LogPath = null;
using (StreamReader file = new System.IO.StreamReader(ConfigPath)) {
while((line = file.ReadLine()) != null) {
if (line.StartsWith("comdir="))
LogPath = line.Substring(7);
}
}
For the configuration file, you might want to consider using a C# class that you serialize as an XML file and then deserialize when launching the application. Then you have the configuration already available within a class whenever you need it.
//Input file path
string inPath = "C:\\Users\\muthuraman\\Desktop\\one_two.config.txt";
//Output File path
string outPath = "C:\\Users\\muthuraman\\Desktop\\log.txt";
// Below code reads all the lines in the text file and Store the text as array of strings
string[] input=System.IO.File.ReadAllLines(inPath);
//Below code write all the text in string array to the specified output file
System.IO.File.WriteAllLines(outPath, input);
Hi Im currently working on my last assignment from a programming class and I'm pretty new to the area of programming. My assignment was to stream a document through Streamreader and extract the information for a menu program to access the document.
So far I have only been able to stream
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
Directory.SetCurrentDirectory(#"\Users\changl\Desktop");
using (StreamReader sr = new StreamReader("earthquakes.csv"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
I'm rather in experienced in the programming and would like some help on what my next step is for saving the information in the document for later use.
Console.Writeline just writes the information out to the console window you need some form of a way to save this..
using (StreamReader sr = new StreamReader("earthquakes.csv"))
{
String line;
List<string> myList = new List<string>();
while ((line = sr.ReadLine()) != null)
{
// Console.WriteLine(line);
myList.add(line);
}
}
You need to just split each line by ,,;,\t:
var fieldsEnumerable = sr.ReadLine().Split(',');
but this library will do it for you:
List<List<string>> records = new List<List<string>>();
using (CsvReader reader = new CsvReader(FilePath, Encoding.Default))
{
while (reader.ReadNextRecord())
records.Add(reader.Fields);
}
I want my program to read from two text files into one List<T>.
The List<T> is sorting and cleaning duplicates.
I want the List<T> to save (after sorting and cleaning) to a txt file.
But when I looked in the result txt file, I found this message:
System.Collections.Generic.List`1[System.String]
Does anyone have an idea how I could fix this error?
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Uniqpass
{
class Program
{
static void Main(string[] args)
{
String pfad = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\";
String pfad2 = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\";
String speichern = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\ausgabe.txt";
String datei = "text1.txt";
String datei2 = "text2.txt";
try
{
//Einlesen TxT 1
List<String> pass1 = new List<String>();
StreamReader sr1 = new StreamReader(pfad + datei);
while (sr1.Peek() > -1)
{
pass1.Add(sr1.ReadLine());
}
sr1.Close();
//Einlesen TxT 2
StreamReader sr2 = new StreamReader(pfad2 + datei2);
while (sr2.Peek() > -1)
{
pass1.Add(sr2.ReadLine());
}
sr2.Close();
List<String> ausgabeListe = pass1.Distinct().ToList();
ausgabeListe.Sort();
ausgabeListe.ForEach(Console.WriteLine);
StreamWriter file = new System.IO.StreamWriter(speichern);
file.WriteLine(ausgabeListe);
file.Close();
}
catch (Exception)
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
}
}
There's a handy little method File.WriteAllLines -- no need to open a StreamWriter yourself:
In .net 4:
File.WriteAllLines(speichern, ausgabeListe);
In .net 3.5:
File.WriteAllLines(speichern, ausgabeListe.ToArray());
Likewise, you could replace your reading logic with File.ReadAllLines, which returns an array of strings (use ToList() on that if you want a List<string>).
So, in fact, your complete code could be reduced to:
// Input
List<String> data = File.ReadAllLines(pfad + datei)
.Concat(File.ReadAllLines(pfad2 + datei2))
.Distinct().ToList();
// Processing
data.Sort();
// Output
data.ForEach(Console.WriteLine);
File.WriteAllLines(speichern, data);
It's this line which writes the ToString representation of the List, resulting into the text line you got:
StreamWriter file = new System.IO.StreamWriter(speichern);
file.WriteLine(ausgabeListe);
file.Close();
Instead you want to write each line.
StreamWriter file = new System.IO.StreamWriter(speichern);
ausgabeListe.ForEach(file.WriteLine);
file.Close();
Loop through the list, writing each line individually:
StreamWriter file = new System.IO.StreamWriter(speichern);
foreach(string line in ausgabeListe)
file.WriteLine(line);
file.Close();
Try the code below:
StreamWriter writer = new StreamWriter("C:\\Users\\Alchemy\\Desktop\\c#\\InputFileFrmUser.csv");
list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};
foreach (var x in list) {
string wr = x.ProductId + " " + x.Name + "" + x.Brand + " " + x.Quantity + " " + x.Price;
writer.Flush();
writer.WriteLine(wr);
}
Console.WriteLine("--------ProductList Updated SucessFully----------------");
You are writing the list object into the file, so you see the type name.
Just as you are using ForEach to write the contents to the Console, you need to iterate over ausgabeListe, calling WriteLine() for each item in the list.
StreamWriter file = new System.IO.StreamWriter(speichern);
foreach(string x in ausgabeListe)
file.WriteLine(x);
file.Close();
I am using the LINQ like below to write each line to text file.
var myList=new List<string>
{
"Hello",
"World"
};
using (var file = new StreamWriter("myfile.txt"))
{
myList.ForEach(v=>file.WriteLine(v));
}
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);
}
}
}