broken diacritic when writing to file [duplicate] - c#

There are a lot of different ways to read and write files (text files, not binary) in C#.
I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings.

Use File.ReadAllText and File.WriteAllText.
MSDN example excerpt:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);

In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
Missing using/Close is very common reason of "why data is not written to file".

FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
using (StreamWriter sw = new StreamWriter(Destination))
{
sw.Writeline("Your text");
}
}

The easiest way to read from a file and write to a file:
//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");
//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
writer.WriteLine(something);
}

using (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
Simple, easy and also disposes/cleans up the object once you are done with it.

#AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:
This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.
using System.IO;//File, Directory, Path
namespace Lib
{
/// <summary>
/// Handy string methods
/// </summary>
public static class Strings
{
/// <summary>
/// Extension method to write the string Str to a file
/// </summary>
/// <param name="Str"></param>
/// <param name="Filename"></param>
public static void WriteToFile(this string Str, string Filename)
{
File.WriteAllText(Filename, Str);
return;
}
// of course you could add other useful string methods...
}//end class
}//end ns
This is how to use the string extension method, note that it refers automagically to the class Strings:
using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
class Program
{
static void Main(string[] args)
{
"Hello World!".WriteToFile(#"c:\temp\helloworld.txt");
return;
}
}//end class
}//end ns
I would never have found this myself, but it works great, so I wanted to share this. Have fun!

These are the best and most commonly used methods for writing to and reading from files:
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.
Append text to an existing file:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
Get file name from the user via file explorer/open file dialog (you will need this to select existing files).
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
Get text from an existing file:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}

Or, if you are really about lines:
System.IO.File also contains a static method WriteAllLines, so you could do:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);

It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:
Don't forget to add the following using statement to read files: using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
To write files you can use the method File.WriteAllText.

class Program
{
public static void Main()
{
//To write in a txt file
File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");
//To Read from a txt file & print on console
string copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
Console.Out.WriteLine("{0}",copyTxt);
}
}

private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}

Reading from file
string filePath = #"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
Writing to file
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);

Simply:
String inputText = "Hello World!";
File.WriteAllText("yourfile.ext",inputText); //writing
var outputText = File.ReadAllText("yourfile.ext"); //reading

You're looking for the File, StreamWriter, and StreamReader classes.

Related

How to search for a file extension (.xls) and change it's name? C#

The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

C# Best Way to Save Text Files into Objects

I have a group of delimited text files I need to read, create a class and objects, and store members inside. I am a beginner that's just looking to be pointed in the right direction. Any help would be appreciated greatly. Thank you very much.
I made a class with objects with:
public string left;
public string right;
and my form code :
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
textBox2.Text = sr.ReadToEnd();
// sr.Close();
}
private void button3_Click(object sender, EventArgs e)
{
string[] split1 = textBox2.Text.Split(';');
foreach (string segment in split1)
{
//split sub-segment
string[] split2 = segment.Split(':');
//check if it's valid
if (split2.Count().Equals(2))
{
id textfile = new id();
textfile.left += // ????
id textfile1 = new id();
textfile.right += // ????
Generally, it's much preferable to use JSON or XML to save data to text files rather than delimited text or custom formats. That's because good JSON and XML support is available in my languages and it's easy to work with.
public class MyCustomClass //this class will hold your data
{
public string Left {get; set;}
public string Right {get;set;}
}
MyCustomClass mcc=new MyCustomClass(); //create an instance of your class
mcc.Left="yes"; //set some properties
mcc.Right="nope";
string json=JsonConvert.SerializeObject(mcc); //convert to JSON string
File.WriteAllText("mcc.txt",json); //save to file
//later on, when you want to read it back from the file
string json=File.ReadAllText("mcc.text"); //read from file into a string
MyCustomClass mcc=JsonConvert.DeserializeObject<MyCustomClass>(json); //convert the string back to an instance of MyCustomClass
Above, we use Json.NET which is a library available for the .NET Framework (available on NuGet). We use it to convert our object to a string (serialize) and then later on to convert it back to an object (deserialize). Note that in order to use the JsonConvert class, you'll need the Json.NET references and to add a using statement at the top of your class using Newtonsoft.Json;.
What you're looking for is serialization. When you have a known structure (like your class with string left and string right), you want to write that structure out to a text file. Then later, you want to read that information back in and automatically populate the class with each of the values.
As mason pointed out, JSON is fairly easy to setup. You create the class structure that you want, and tell JSON to save that out to a specified file (via SerializeObject).
Since .NET allows for reflection, JSON is able to turn the text file back into the contents of a class without you having to manually 'myClass.left = [some_value_from_json]'.
Personally, I'd go with JSON or XML, since naming your blocks of data means it is both more readable, and that your parser is able to handle someone rearranging the data (it doesn't matter if the file defines left before it defines right). If you rearranged a .CSV file, then you get data corruption.
Reading delimited files is common and there are many approaches to the subject. Personally I use a streamReader to read in the file and split it on the delimiter:
Foo foo = new Foo(); // custom class
string file = "export.CSV";
if (System.IO.File.Exists(file))
{
// Do work
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
// split on the delimeter
var readLine = reader.ReadLine();
if (readLine == null) continue;
var lines = readLine.Split(new[] { ',' });
foreach (string s in lines)
{
// do something with the data from the line
}
// alternatively, you could specify your objects if your files
// layout never changes. Just be careful to catch the exceptions!
foo.bar = lines[0];
foo.baz = lines[1];
}
}
}

Read text file from C# Resources

I need to read a file from my resources and add it to a list.
my code:
private void Form1_Load(object sender, EventArgs e)
{
using (StreamReader r = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt")))
{
//The Only Options Here Are BaseStream & CurrentEncoding
}
}
Ive searched for this and only have gotten answers like "Assembly.GetExecutingAssembly...." but my program doesnt have the option of Assembly.?
Try something like this :
string resource_data = Properties.Resources.test;
List<string> words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList();
Where
You need to include using System.Reflection; in your header in order to get access to Assembly. This is only for when you mark a file as "Embedded Resource" in VS.
var filename = "MyFile.txt"
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNameSpace." + filename));
As long as you include 'using System.Reflection;' you can access Assembly like this:
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + filename);
Or if you don't need to vary filename just use:
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.MyFile.txt");
The full code should look like this:
using(var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.m‌​yText.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do some stuff here with your textfile
}
}
Just to follow on this, AppDeveloper solution is the way to go.
string resource_data = Properties.Resources.test;
string [] words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
foreach(string lines in words){
.....
}
[TestCategory("THISISATEST")]
public void TestResourcesReacheability()
{
byte[] x = NAMESPACE.Properties.Resources.ExcelTestFile;
string fileTempLocation = Path.GetTempPath() + "temp.xls";
System.IO.File.WriteAllBytes(fileTempLocation, x);
File.Copy(fileTempLocation, "D:\\new.xls");
}
You get the resouce file as a byte array, so you can use the WriteAllBytes to create a new file. If you don't know where can you write the file (cause of permissions and access) you can use the Path.GetTempPath() to use the PC temporary folder to write the new file and then you can copy or work from there.

Processing multiple drag and dropped files fails when using regular expressions

In my application the user can drag and drop multiple text files onto a GUI control to convert them to another format. Here is the relevant code:
private void panelConverter_DragDrop(object sender, DragEventArgs e)
{
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string filename in filenames)
{
convertFile(filename);
}
}
private void convertFile(string filename)
{
// build name of output file
string convertedFile = Path.ChangeExtension(filename, ".out");
// open input file for reading
FileInfo source = new FileInfo(filename);
StreamReader srcStream = source.OpenText();
// open output file for writing
StreamWriter dstStream = new StreamWriter(convertedFile);
// loop over input file
string line;
do
{
// get next line from input file
line = srcStream.ReadLine();
if (!Regex.IsMatch(line, #"fred=\d+"))
{
dstStream.WriteLine(line);
dstStream.Flush();
}
} while (line != null);
}
The problem is that when I drop multiple files on the GUI, only one of them actually gets processed. I have found that if I comment out the Regex line, all of the dropped files are processed. Am I missing something in my handling of regular expressions in this context?
Try following variation of the method:
private void convertFile(string filename)
{
// build name of output file
string convertedFile = Path.ChangeExtension(filename, ".out");
// open input file for reading
FileInfo source = new FileInfo(filename);
StreamReader srcStream = source.OpenText();
// open output file for writing
using (StreamWriter dstStream = File.CreateText(convertedFile))
{
// loop over input file
string line;
do
{
// get next line from input file
line = srcStream.ReadLine();
if (!Regex.IsMatch(line, #"fred=\d+"))
{
dstStream.WriteLine(line);
dstStream.Flush();
}
} while (line != null);
}
Debug.WriteLine(string.Format("File written to: {0}", convertedFile));
}
The main modification is use of using keyword which would guarantee disposal and closing of the file resource. If problem is not still resolved then try followings:
Do you have any global exception handlers? Make sure you check Debug > Exceptions... so that Visual Studio automatically breaks on the line where exception is thrown. See this article on how-to.
Make sure files are written at correct places. If files have full path then the Debug.WriteLine statement above would tell you were the files are being written.
You should get at least 0 length file written on the disk if no exceptions are occurring.

C# - Appending text files

I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)
private static void Ignore()
{
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
Console.WriteLine(myString);
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
file.WriteLine(myString);
file.Close();
}
If the file is small, you can read and write in two code lines.
var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);
If the file is huge, you can read and write line-by-line:
using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
var line = source.ReadLine();
destination.WriteLine(line);
}
using(StreamWriter file = File.AppendText(#"c:\test2.txt"))
{
file.WriteLine(myString);
}
Use File.AppendAllText
File.AppendAllText("c:\\test2.txt", myString)
Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.
Try
StreamWriter writer = File.AppendText("C:\\test.txt");
writer.WriteLine(mystring);

Categories

Resources