I have a function to write a message to text file. But when passing a string with 'Environment.NewLine', it is not writes a new line to the text file. Instead it writes '\r\n'.
How to correct this? I have tried with '\n' instead of 'Environment.NewLine'. Still the new line is not coming.
The issue is happens only when passing a string with new line to the function. Like variable 'message'
string message= "First "+Environment.NewLine+" message.";
LogTheDetails(message);
public static void LogTheDetails(String message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("============================================================\n --Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND LINES
{
string testString= "testString"+ Environment.NewLine+ "WithNewLine";
File.AppendAllText(FilePath, "\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath, "\n============================================================\n");
}
}
Output
============================================================
--Logs--
============================================================
First \r\n message.
testString
WithNewLine
============================================================
Expected Output:
============================================================
--Logs--
============================================================
First
message.
testString
WithNewLine
============================================================
Below piece of code gave the output you are looking for, I tried it in .net 5 console application.
using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static string message = "First " + Environment.NewLine + " message.";
static void Main(string[] args)
{
LogTheDetails(message);
Console.WriteLine("Hello World!");
}
public static void LogTheDetails(string message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string currentdate = "test";
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("========================================================\n
--Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND
LINES
{
string testString = Environment.NewLine + "testString" +
Environment.NewLine + "WithNewLine";
File.AppendAllText(FilePath,
"\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath,
"\n============================================================\n");
}
}
}
}
Related
All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace RandomName
{
class Program
{
static void Main(string[] args)
{
string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";
string fileName = "file1.txt";
StreamReader reader = new StreamReader(winDir + fileName);
string outputFileName = "upperfile" + fileName;
StreamWriter writer = new StreamWriter(outputFileName);
int n = 0;
string st = "";
string upperString = "";
int n2 = 0;
string st2 = "";
string upperString2 = "";
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2;
StreamWriter writer2 = new StreamWriter(outputFileName2);
do
{
++n;
st = reader.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n + ": " + st); // write to the console
writer.WriteLine(st); // write line to disk file instead, using WriteLine() method
upperString = upperString + "\n" + st; // append each line to the big string
}
while (!reader.EndOfStream);
do
{
++n2;
st2 = reader2.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n2 + ": " + st2); // write to the
console
writer2.WriteLine(st2); // write line to disk file instead,
using WriteLine() method
upperString2 = upperString2 + "\n" + st2; // append each line
to the big string
}
while (!reader2.EndOfStream);
reader.Close();
writer.Close();
Console.WriteLine("\nHere is the entire file in a string:");
Console.WriteLine(upperString);
Console.WriteLine(upperString2);
UpperString b = new UpperString(upperString);
UpperString2 c = new UpperString2(upperString2);
Console.WriteLine("\nThe string in reverse case: ");
b.showReverseCase();
Console.WriteLine("\n");
c.readingFile2();
c.toNewFile2();
}
}
}
"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.
Here is the class
class UpperString2
{
private string upperString2;
public UpperString2() { }
public UpperString2(string c) { upperString2 = c; }
public void readingFile2()
{
string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");
System.Console.WriteLine("\nAnother Poem \n");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine(line);
}
}
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!
The problem is "outputfile2" was already opened by reader2 in Main().
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)
Then it raises an exception when you try to open the same file for writting in toNewFile2():
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.
Since you have moved the code to a class, call that class instead.
I am getting an error when I run this newFile method:
class logFile
{
public static string logpath = #"D:\Program Files\CustomApps\DataFeed\";
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss");
Console.WriteLine(timestamp + log);
File.AppendAllText(logpath + #"log_file_current.txt", timestamp + log + Environment.NewLine);
}
public static void newFile()
{
if (File.Exists(logpath + #"log_file_current.txt") == true)
{
File.Move(logpath + #"log_file_current.txt"
, logpath + #"log_files\log_file_ORPHANED_" + DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ".txt");
}
try
{
File.Create(logpath + #"log_file_current.txt");
logFile.log("logFile created.");
}
catch(System.NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
I get the following error:
If I comment the body of the "newFile" code out then it runs without error, but then I would need to manually archive. If I comment out the File.Move part it all runs fine so this is the culprit.
How can I release the file so that it can be moved?
You need to use File.Close after using File.Create, this is why you are getting an error saying the file is used by another process. Try adding this line to your code :
try
{
File.Create(logpath + #"log_file_current.txt").Close(); // Notice the .Close() here
logFile.log("logFile created.");
}
Source : Closing a file after File.Create
Try this one
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ": ";
Console.WriteLine(timestamp + log);
using (StreamWriter sw = File.AppendText(logpath + #"log_file_current.txt"))
{
sw.WriteLine(timestamp + log);
}
}
I wanted to write a text to file using StreamWriter.But Filename should be current date name.
here is my coding.Can somebody tell me how to specify the file creation path?
Code Edit :
In here i wanted to create a .txt file but in here file not created.
public void WriteToFile( string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
if (!File.Exists(filename))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(filename))
{
using (var str = new StreamWriter(filename))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
you need to make following changes
1.Replace ResolveUrl with Server.MapPath
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
2.Add the file extension .txt as shown below
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now,name);
3.when you are checking whether file exists or not provide the path of the file , instead of filename
File.Exists(path);
4.under the else if block , here also provide the path , instead of filename
var str = new StreamWriter(path));
putting all together the code looks like,
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now, name);
string path = Path.Combine(directory, filename);
if (!File.Exists(path))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(path))
{
using (var str = new StreamWriter(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
File.Create returns FileStream, and you need StreamWriter. You'll have to use its constructor that accepts Stream:
using (var str = new StreamWriter(File.CreateText(path)))
Simplify, use FileStream to create or overwrite your file (see below) depending on your neeeds you might want to change the FileMode to be something else (Append ?)
public void WriteToFile(string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
using (FileStream fs = new FileStream(path, FileMode.Create))
{
using (StreamWriter str = new StreamWriter(fs))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
}
Let's say your console app project name is DataPrep. Now you can write in Data directory location by creating a new file namely as db.json
string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, #"..\..\..\")) + #"Data\db.json";
if (!File.Exists(filePath))
{
using (StreamWriter _streamWriter = File.CreateText(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}
else if (File.Exists(filePath))
{
using (var _streamWriter = new StreamWriter(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}
I asked guru but I still couldn't solve the problem that I have.
I want to write a console program searching certain files, like xls, doc or *pdf.
I wrote a code like this but when it comes to the say, Users Directory, it cates UnauthorizedAccessException.
How can I write a console application which can search Users Directory?
I set clickonce off and build it with manifest which requireAdministrator.
So, on Vista or 7, it runs as an administrator, with the elevation dialogue.
Here's the full code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
//
private const string FILE_NAME = "search.txt";
private const string SEARCH_WORDS1 = "*.doc";
private const string SEARCH_WORDS2 = "*.ppt";
private const string SEARCH_WORDS3 = "*.jtd";
private const string SEARCH_WORDS4 = "*.pdf";
private const string END_WORDS = "\r\nSearch is finished.\r\n";
//This funcion echoes the messages.
void FileCheck()
{
string echo_words = "\r\nNow starts searching these files!" + SEARCH_WORDS1 + " "
+ SEARCH_WORDS2 + " " + SEARCH_WORDS3 + " " + SEARCH_WORDS4 + " "
+ "!\r\n";
if (File.Exists(FILE_NAME))
{
Console.WriteLine("{0} is already exists. Replace it to the new one.", FILE_NAME);
Console.WriteLine(echo_words);
File.Delete(FILE_NAME);
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
sw.WriteLine(FILE_NAME + " is already exists. Replace it to the new one.\r\n");
sw.WriteLine(echo_words);
sw.Close();
}
}
else
{
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
Console.WriteLine(echo_words);
sw.WriteLine(echo_words);
sw.Close();
}
}
}
//This function write to a file that search is finished.
void EndMessage()
{
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
Console.WriteLine(END_WORDS);
sw.WriteLine(END_WORDS);
sw.Close();
}
}
//This function searches files given and write to a file.
void DirSearch(string sDir, string SEARCH_WORDS, int row)
{
int i;
i = 0;
string DeviceError = "off";
try
{
foreach (var d in Directory.GetDirectories(sDir))
{
DirectoryInfo di = new DirectoryInfo(d);
if ((di.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
//ReparsePoint could not be serached
continue;
}
try
{
foreach (string file in Directory.GetFiles(d, SEARCH_WORDS, SearchOption.AllDirectories))
{
Console.WriteLine(file);
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(file);
sw.Close();
i++;
}
}
}
catch (UnauthorizedAccessException)
{
//Unauthorized
Console.WriteLine(d + " is not allowd to be read !!");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(d + " is not allowd to be read");
sw.Close();
}
}
}
}
catch (IOException)
{
//Device is not ready
DeviceError = "on";
}
if (DeviceError == "off")
{
if (i > 0)
{
Console.WriteLine(i + "numbers " + SEARCH_WORDS + " Files were found!\r\n");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(i + "numbers " + SEARCH_WORDS + " Files were found!\r\n");
sw.Close();
}
}
else
{
Console.WriteLine(SEARCH_WORDS + " Files were not found !\r\n");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(SEARCH_WORDS + " Files were not found !\r\n");
sw.Close();
}
}
}
}
//Main
static void Main(string[] args)
{
Program x = new Program();
string[] drives = Environment.GetLogicalDrives();
int row = drives.GetLength(0);
string my_documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Console.WriteLine("Logical Drives are " + row + ".");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine("Logical Drives are " + row + ".");
sw.Close();
}
int i = 0;
x.FileCheck();
while (row > 0)
{
x.DirSearch(drives[i], SEARCH_WORDS1, row);
x.DirSearch(drives[i], SEARCH_WORDS2, row);
x.DirSearch(drives[i], SEARCH_WORDS3, row);
x.DirSearch(drives[i], SEARCH_WORDS4, row);
row--;
i++;
}
x.EndMessage();
}
}
}
The error you're getting is caused by the file system permissions. The only way around would be to grant the credentials you're using access to the specified folders, run the application as 'Administrator' or run the application as the specific user for each User's folder.
This is a WinForm written in C#.
Lets say I'm generating a random named text file in my selected directory. When the button is clicked teh first time, i write the data contained in the textboxes into that text file. If the user wants to do the same thing with different data in the textboxes then the click on the button should write the new data into the text file without losing the old data. It's like keeping logs, is this possible?
My code is like:
private readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt");
wFile.WriteLine("Name Surname:" + text1.Text + text2.Text);
wFile.WriteLine("Other:" + text3.Text + text4.Text);
wFile.WriteLine("Money:" + textBox1.Text + " TL.");
wFile.WriteLine("*************************************");
wFile.Close();
}
else
{
return;
}
}
You can append to the text in the file.
See
File.AppendText
using (StreamWriter sw = File.AppendText(pathofFile))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
where pathofFile is the path to the file to append to.
Have a look at using something like this:
StreamWriter fw = new StreamWriter(#"C:\Logs\MyFile.txt",true);
fw.WriteLine("Some Message" + Environment.Newline);
fw.Flush();
fw.Close();
Hope that helps. See MSDN StreamWriter for more information
Updated: Removed old example
Also if you are trying to create a unique file you can use Path.GetRandomFileName()
Again from the MSDN Books:
The GetRandomFileName method returns a
cryptographically strong, random
string that can be used as either a
folder name or a file name.
UPDATED: Added a Logger class example below
Add a new class to your project and add the following lines (this is 3.0 type syntax so you may have to adjust if creating a 2.0 version)
using System;
using System.IO;
namespace LogProvider
{
//
// Example Logger Class
//
public class Logging
{
public static string LogDir { get; set; }
public static string LogFile { get; set; }
private static readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Logging() {
LogDir = null;
LogFile = null;
}
public static string RandomFileName()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
public static void AddLog(String msg)
{
String tstamp = Convert.ToString(DateTime.Now.Day) + "/" +
Convert.ToString(DateTime.Now.Month) + "/" +
Convert.ToString(DateTime.Now.Year) + " " +
Convert.ToString(DateTime.Now.Hour) + ":" +
Convert.ToString(DateTime.Now.Minute) + ":" +
Convert.ToString(DateTime.Now.Second);
if(LogDir == null || LogFile == null)
{
throw new ArgumentException("Null arguments supplied");
}
String logFile = LogDir + "\\" + LogFile;
String rmsg = tstamp + "," + msg;
StreamWriter sw = new StreamWriter(logFile, true);
sw.WriteLine(rmsg);
sw.Flush();
sw.Close();
}
}
}
Add this to your forms onload event
LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings";
LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();
Now adjust your button click event to be like the following:
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StringBuilder logMsg = new StringBuilder();
logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine);
logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine);
logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine);
logMsg.Append("*************************************" + Environment.NewLine);
LogProvider.Logging.AddLog(logMsg.ToString());
} else
{
return;
}
Now you should only create one file for the entire time that application is running and will log to that one file every time you click your button.
You might want to take a look at log4net and the RollingFileAppender
Sure. Just open the file for appending with something like System.IO.File.AppendText