I am trying to get the following: [today's date]___[textfilename].txt from the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
WriteToFile();
}
static void WriteToFile()
{
StreamWriter sw;
sw = File.CreateText("c:\\testtext.txt");
sw.WriteLine("this is just a test");
sw.Close();
Console.WriteLine("File created successfully");
}
}
}
I tried putting in DateTime.Now.ToString() but i cannot combine the strings.
Can anybody help me? I want the date in FRONT of the title of the new text file I am creating.
static void WriteToFile(string directory, string name)
{
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, name);
string path = Path.Combine(directory, filename);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("This is just a test");
}
}
To call:
WriteToFile(#"C:\mydirectory", "myfilename");
Note a few things:
Specify the date with a custom format string, and avoid using characters illegal in NTFS.
Prefix strings containing paths with the '#' string literal marker, so you don''t have to escape the backslashes in the path.
Combine path parts with Path.Combine(), and avoid mucking around with path separators.
Use a using block when creating the StreamWriter; exiting the block will dispose the
StreamWriter, and close the file for you automatically.
You'd want to do a custom string format on DateTime.Now. You can use String.Format() to combine the results of that with your base filename.
To append on the path to the filename, use Path.Combine().
Finally, use a using() block to properly close & dispose your StreamWriter when you are finished with it...
string myFileName = String.Format("{0}__{1}", DateTime.Now.ToString("yyyyMMddhhnnss"), "MyFileName");
strign myFullPath = Path.Combine("C:\\Documents and Settings\\bob.jones\\Desktop", myFileName)
using (StreamWriter sw = File.CreateText(myFullPath))
{
sw.WriteLine("this is just a test");
}
Console.WriteLine("File created successfully");
Edit: fixed sample to account for path of "C:\Documents and Settings\bob.jones\Desktop"
Try this:
string fileTitle = "testtext.txt";
string fileDirectory = "C:\\Documents and Settings\username\My Documents\";
File.CreateText(fileDirectory + DateTime.Now.ToString("ddMMYYYY") + fileTitle);
?
To answer the question in your comment on #Scott Ivey's answer:
to specify where the file is written to, prepend the desired path to the file name before or in the call to CreateText().
For example:
String path = new String (#"C:\Documents and Settings\bob.jones\Desktop\");
StreamWriter sw = File.CreateText(path + myFileName);
or
String fullFilePath = new String (#"C:\Documents and Settings\bob.jones\Desktop\");
fullFilePath += myFileName;
StreamWriter sw = File.CreateText(fullFilePath);
Related
While learning with books sometimes i copy some code from pdf, to test it.
This tiny exe was suppose to change ‘ ’ “ ” to ' or "
and it work fine, but only if tested *.cs file is opened manually before I debug my methods.
Otherwise it's not working. When code paste into concerned file directly, and closed, without opening once again The Replace method return "Unexpected character ?"
I dont understand the probleme, since File.ReadAllText already open and close the file.
using System;
using System.Collections.Generic;
using System.IO;
class Test
{
public static void Main()
{
string path = Directory.GetCurrentDirectory();
string[] csfiles = Directory.GetFiles(path, "*.cs");
foreach (var item in csfiles)
{
string text = File.ReadAllText(item);
text = text.Replace("‘", "\'")
.Replace("’", "\'")
.Replace("“", "\"")
.Replace("”", "\"");
File.WriteAllText(item, text);
}
}
}
Apparently File.ReadAllText(); does change encoding when opening.
My caracters (being in ASCII+ANSI) was ruined just when opened.
string text = File.ReadAllText(path, Encoding.Default); keeps original encoding when opening. Replace work fine on this, and so my exe.
:) Thank you for your help!
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = Directory.GetCurrentDirectory();
string[] csfiles = Directory.GetFiles(path, "*.cs");
foreach (var item in csfiles)
{
string text = File.ReadAllText(item, Encoding.Default);
string newtext = text.Replace("‘", "\'")
.Replace("’", "\'")
.Replace("“", "\"")
.Replace("”", "\"");
File.WriteAllText(item, newtext);
}
}
}
How to read an ANSI encoded file containing special characters
In the code included below, I am able to write the contents of the string 'fullname' to a text file in the specified directory when using the following statement:
System.IO.File.WriteAllText(path, fullname);
However, if I write the string path to a FileStream object (withe arguments specified), and then pass that FileStream object as an argument to the StreamWriter object, the file is created, but no contents are written.
First attempt: Comment out System.IO.File.WriteAllText(path, fullname); and use the three lines above it. This creates the file but no contents are written into the file.
Second attempt: Un-comment the System.IO.File.WriteAllText(path, fullname); statement and comment the three lines above it. This executes as desired.
Here is the full block of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
class Program
{
static void Main(string[] args)
{
// Use the Split() method of the String Class
string fullname = " Robert Gordon Orr ";
fullname = fullname.Trim();
string[] splitNameArray = fullname.Split(' ');
Console.WriteLine("First Name is: {0}", splitNameArray[0]);
Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
Console.WriteLine("Full name is: {0}", fullname);
string path = #"C:\Programming\C#\C# Practice Folder\Console Applications\FileInputOutput\textfile.txt";
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
StreamWriter toFile = new StreamWriter(fs);
toFile.Write(fullname);
//System.IO.File.WriteAllText(path, fullname);`enter code here`
Console.ReadLine();
}
}
}
As others have said: streams must be flushed in .NET in order for them to write to disk. This can be done manually, however I would simply change your code to have using statements on your streams:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
class Program
{
static void Main(string[] args)
{
// Use the Split() method of the String Class
string fullname = " Robert Gordon Orr ";
fullname = fullname.Trim();
string[] splitNameArray = fullname.Split(' ');
Console.WriteLine("First Name is: {0}", splitNameArray[0]);
Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
Console.WriteLine("Full name is: {0}", fullname);
string path = #"C:\textfile.txt";
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter toFile = new StreamWriter(fs))
{
toFile.Write(fullname);
}
}
//System.IO.File.WriteAllText(path, fullname);`enter code here`
Console.ReadLine();
}
}
}
Calling Dispose() on a stream (as using implicitly does), causes the stream to be flushed and closed at the end of the using block.
I think you are just forgetting to flush your file stream:
fs.Flush();
This is needed because according to msdn, this is what makes the FileStream to actually write the buffer to the file.
Flush: Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush().)
Regards.
From MSDN on StreamWriter
You must call Close to ensure that all data is correctly written out to the underlying stream.
So the problem here is mainly that, since you don't actually close the StreamWriter, the data gets backed up but doesn't push to the file, even though the FileStream immediately created the file in its constructor. Never ever forget to close your stream, as failing to do so could lead to major problems down the line.
I'm currently working on a utility to parse multiple xml files and write the results to a csv file. On the second last line(of code) I get the error:
The process cannot access the file 'W:\SRC\hDefML\myExcelFile.csv' because it is being used by another process.'.
Can someone please help me because I have no idea what's wrong, the file isn't being used by anything else and it's driving me crazy?
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace GenNameUtility
{
class NameGenerator
{
static void Main(string[] args)
{
var files = from file in Directory.GetFiles("W:\\SRC\\hDefMl\\1.0\\Instrument_Files") orderby file
ascending select file;
StringBuilder sb_report = new StringBuilder();
string delimiter = ",";
sb_report.AppendLine(string.Join(delimiter, "Module", "Generator(s)"));
foreach (var file in files)
{
string filename = Path.GetFileNameWithoutExtension(file);
Console.Write("The HDefML file for {0} contains these EEPROM Generators:", filename);
XDocument hdefml = XDocument.Load(file);
var GeneratorNames = from b in hdefml.Descendants("Generators") select new
{
name = (string)b.Element("GeneratorName")
}.ToString();
StringBuilder sb = new StringBuilder();
foreach (var item in GeneratorNames)
{
Console.Write(" GeneratorName is: {0}", GeneratorNames);
sb_report.AppendLine(string.Join(delimiter, filename, GeneratorNames));
var hdef = File.Create(#"W:\SRC\hDefML\myExcelFile.csv").ToString();
File.WriteAllText(hdef, sb.ToString());
}
}
Console.ReadLine();
}
}
}
You need to close the file after you have written to it. See using.
Also it would be better to open the file before the loop and close it thereafter.
The file is being used by another process... but the process is actually yours.
File.Create returns a FileStream. You're opening the file.. writing to it.. but not closing it. When the new iteration comes around.. the file is still open.
You can try something like this:
using (var file = File.Create(#"W:\SRC\hDefML\myExcelFile.csv")) {
// write content here using file
} // this closes the file automatically.
As suggested though, I would wrap the above outside of the loop, so you're not constantly opening and closing the file.
File.WriteAllText will create a file for you so there's no need to use File.Create beforehand.
File.WriteAllText(#"W:\SRC\hDefML\myExcelFile.csv", sb.ToString());
Your File.Create stream seems to be holding the lock on the file which is why File.WriteAllText is throwing the error.
If you need to use File.Create you can use a StreamWriter to write it out.
using(var fs = File.Create(#"W:\SRC\hDefML\myExcelFile.csv"))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(sb.ToString());
}
as a side note, the above using format is the same as doing
using(var fs = File.Create(#"W:\SRC\hDefML\myExcelFile.csv"))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(sb.ToString());
}
}
so you can use whichever you find more readable.
The following program should open/create a file and write the current date to it's end every time.
using System;
using System.IO;
using System.Text;
namespace roughDraft
{
class Program
{
public static void Main()
{
StreamWriter oFile = File.AppendText("baza.txt");
string output = "Current date and time: " + DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");
oFile.WriteLine(output);
Console.WriteLine(output);
Console.ReadKey();
}
}
}
I don't know why does it only create an empty file.
You should always put StreamWriter objects in a using statement so they get closed properly.
using (StreamWriter oFile = File.AppendText("baza.txt"))
{
string output = "Current date and time: "
+ DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");
oFile.WriteLine(output);
}
Alternatively, you can manually call the Close method on the StreamWriter, but the using statement, to me, is much easier and less error-prone.
Its creating empty file because you are writing in it but not closing the StreamWriter
like this oFile.Close();
I'm not sure what exactly i'm doing wrong here...but i noticed that my File.Move() isn't renaming any files.
Also, does anybody know how in my 2nd loop, i'd be able to populate my .txt file with a list of the path AND sanitized file name?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//recurse through files. Let user press 'ok' to move onto next step
string[] files = Directory.GetFiles(#"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
Console.Write(file + "\r\n");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
//End section
//Regex -- find invalid chars
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
string replacement = " ";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(#"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
//clean out file -- remove the path name so file name only shows
string result;
foreach(string fileNames in fileDrive)
{
result = Path.GetFileName(fileNames);
filePath.Add(result);
}
StreamWriter sw = new StreamWriter(#"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt");
//Sanitize and remove invalid chars
foreach(string Files2 in filePath)
{
try
{
string sanitized = regEx.Replace(Files2, replacement);
sw.Write(sanitized + "\r\n");
System.IO.File.Move(Files2, sanitized);
System.IO.File.Delete(Files2);
}
catch (Exception ex)
{
Console.Write(ex);
}
}
sw.Close();
}
}
}
I'm VERY new to C# and trying to write an app that recurses through a specific drive, finds invalid characters (as specified in the RegEx pattern), removes them from the filename and then write a .txt file that has the path name and the corrected filename.
Any ideas?
Your filepath list contains only the file names. You have removed the directory info from them in the call to Path.GetFileName(), so your File.Move is looking for the target file in the application's default directory, rather than its original location.
I think your code for saving the sanitized file names is correct though. You should use the using() construct around your StreamWriter though, as below, to ensure that the file is closed once you're done with it.
//clean out file -- remove the path name so file name only shows
string result;
foreach(string fileNames in fileDrive)
{
// result = Path.GetFileName(fileNames); // don't do this.
filePath.Add(fileNames);
}
using (StreamWriter sw = new StreamWriter(#"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt"))
{
//Sanitize and remove invalid chars
foreach(string Files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(Files2);
string pathOnly = Path.GetDirectoryName(Files2);
string sanitizedFilename = regEx.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFilename);
sw.Write(sanitized + "\r\n");
System.IO.File.Move(Files2, sanitized);
}
catch
{
}
}
}
Are any exceptions being thrown in the call to File.Move()? You have an empty catch block beneath it which will be stopping you from seeing them. Try removing the catch{} or putting some code in there to log any exceptions.
Try using File.AppendAllLines() (with a collection) or File.AppendAllText() (for each individually) instead of a stream. That will make things a little easier.
Also, I understand not wanting your application to bomb, but at the very least, while you're currently writing/debugging comment your try block out so that you can see the exceptions.
Probably not an answer, but perhaps a suggestion to help.