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);
}
}
Related
This question already has answers here:
How to read an entire file to a string using C#?
(17 answers)
Closed 3 years ago.
There are some function that read all text from file without use FileStream class and more easy?
In microsoft doc found this code to read from file but I think is some complexed.
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
string filename = #"C:\Example\existingfile.txt";
char[] result;
StringBuilder builder = new StringBuilder();
using (StreamReader reader = File.OpenText(filename))
{
result = new char[reader.BaseStream.Length];
await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length);
}
foreach (char c in result)
{
if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c))
{
builder.Append(c);
}
}
FileOutput.Text = builder.ToString();
}
Please see the File.ReadAllText Method.
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText, Encoding.UTF8);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText, Encoding.UTF8);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
I have text file which i need to update according to the regex match but as soon as my program tries to write a line into text file it is giving following error..
The process cannot access the file 'D:\Archieve\20140123.text' because it is being used by another process.
Here is my C# code..
static void Main(string[] args)
{
string textfilename="";
string strDateTime = DateTime.Now.ToString("yyyyMMdd");
string strformatedatetime = DateTime.Now.ToString("yyyy/MM/dd");
if (strDateTime != "") {
string loc = "D:\\Archieve\\";
string date=strDateTime;
string text=".text";
textfilename = loc + date + text;
File.Create(textfilename);
}
string pattern = "^" + strformatedatetime + ".*";
string FileToCopy = "D:\\ipdata.txt";
string NewCopy =textfilename;
StringBuilder sb = new StringBuilder("");
List<string> newLines = new List<string>();
if (System.IO.File.Exists(FileToCopy) == true)
{
string[] lines = File.ReadAllLines(FileToCopy);
foreach (string line in lines)
{
if (Regex.IsMatch(line, pattern))
{
sb.Append(line + System.Environment.NewLine);
TextWriter tsw = new StreamWriter(textfilename,true);
//Writing text to the file.
tsw.WriteLine(sb);
//Close the file.
tsw.Close();
}
}
}
}
I am getting above defined error at this line of code...
TextWriter tsw = new StreamWriter(textfilename,true);
Where am i going wrong ?
You don't need to have a separate instruction to create a file.
The StreamWriter will take care of it: Here is the description of the constructor you user
> Initializes a new instance of the StreamWriter class for the specified
> file by using the default encoding and buffer size. If the file
> exists, it can be either overwritten or appended to. If the file does
> not exist, this constructor creates a new file.
Use File.Create(textfilename).Close();
As the error message suggests
I am trying to read a list in text file and move the files source to target directory. But as I am trying to read this file using for statement it's giving me following error :
foreach statement cannot operate on variables of type
System.IO.StreamReader because System.IO.StreamReader does not
contain a public definition for GetEnumerator
Not sure if this is issue with file creation or some alternate approach is needed here to read and then move files.
Please advise.
Here's the code:
static void Main(string[] args)
{
create_source_fileList();
string source_dir = System.Configuration.ConfigurationSettings.AppSettings["SourceDir"];
string target_dir = System.Configuration.ConfigurationSettings.AppSettings["TargetDir"];
string dpath = target_dir + "Diff" + ".txt";
TextWriter df = new StreamWriter(dpath);
DirectoryInfo sourceinfo = new DirectoryInfo(source_dir);
DirectoryInfo targetinfo = new DirectoryInfo(target_dir);
string[] source_f_list = File.ReadAllLines(target_dir + "Source_File_List.txt");
string[] target_f_list = File.ReadAllLines(target_dir + "Target_File_List.txt");
IEnumerable<String> file_list_diff = source_f_list.Except(target_f_list);
string diff_list = string.Join(Environment.NewLine, file_list_diff);
df.WriteLine(string.Join(Environment.NewLine, file_list_diff));
df.Close();
System.IO.StreamReader file_read = new System.IO.StreamReader(target_dir + "\\Diff.txt");
if (!Directory.Exists(targetinfo.FullName))
{
Directory.CreateDirectory(targetinfo.FullName);
}
/*foreach (FileInfo fi in sourceinfo.GetFiles())
{
fi.CopyTo(Path.Combine(targetinfo.ToString(), fi.Name), true);
}*/
foreach (string file in file_read) // Error With For Loop
{
}
create_target_fileList();
}
Yes, you can't use foreach directly with StreamReader. It doesn't have the required members for foreach to work.
Options:
Use File.ReadLines instead:
string path = Path.Combine(targetDir, "Diff.txt");
foreach (string file in File.ReadLines(path))
{
// ...
}
Repeatedly call ReadLine on your StreamReader, which should be in a using statement and is simply obtained using File.OpenText:
string path = Path.Combine(targetDir, "Diff.txt");
using (TextReader reader = File.OpenText(path))
{
string file;
while ((file = reader.ReadLine()) != null)
{
// ...
}
}
Note that I've made the variable names a bit cleaner too - idiomatic variable names in C# are things like sourceFileList rather than source_f_list.
Additionally, I'd encourage you to use File.WriteAllText earlier on, rather than the way you're using df (without a using statement, and opening it much earlier than you need to).
I am new to C#. How can I write data into one file? This is my code so far:
public void convertHTML(string strData, string strTitle)
{
int position = strTitle.LastIndexOf('.');
strTitle = strTitle.Remove(position);
strTitle= strTitle + ".html";
StreamWriter sw = new StreamWriter(strTitle); //strTitle is FilePath
sw.WriteLine("<html>");
sw.WriteLine("<head><title>{0}</title></head>",strTitle);
//MessageBox.Show("this editor");
sw.WriteLine("<body>");
sw.WriteLine(strData); //strData is having set of lines
sw.WriteLine("</body>");
sw.WriteLine("</html>");//*/
lstHtmlFile.Items.Add(strTitle);
}
it will simply create one blank html file it won't have any data
You need to flush and close the StreamWriter:
using (StreamWriter sw = new StreamWriter(strTitle))
{
sw.WriteLine("<html>");
sw.WriteLine("<head><title>{0}</title></head>",strTitle);
sw.WriteLine("<body>");
sw.WriteLine(strData);
sw.WriteLine("</body>");
sw.WriteLine("</html>");
}
Using using does the trick.
You can add block using in order to clean your non managed object
using (var streamWriter = new StreamWriter(strTitle))
{
....
}
Link : http://msdn.microsoft.com/fr-fr/library/vstudio/yh598w02.aspx
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();
}