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();
Related
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.
I want to launch my soft directly by open a file with a specific extension (here no problem) but I was wondering how read directly the content of this file ?
I checked on internet but nothing useful came out.
Thanks
Try to use the File class, in particular the File.ReadAllText Method
Sample MSDN usage
using System;
using System.IO;
using System.Text;
class Test
{
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);
}
// 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);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
In order to read the file name from the command line (invoked on double click)
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main(string[] args)
{
Console.Writeline("I bet your filename is: {0}", args[0]);
}
}
See also this very nice example.
File.ReadAllLines is waht your looking for, you should provide an Serilizer to get your spezific data from that file.
But what do you want do read from that file? if it is an executable i think you don't want to read that file or?
Well, first of all my code :
protected void Button2_Click1(object sender, EventArgs e)
{
string batname = edit.SelectedValue;
StreamWriter sw = new StreamWriter("D:\\MPSite-Serv\\bats\\" + batname);
string theedit = batedit.Text;
sw.WriteLine(theedit);
sw.Flush();
}
When I click on button2 and try to write all of the text into the bat file, I get this result the bat file contains:
System.Web.UI.WebControls.TextBox
Why is that?
I am using all of the following statements, if it helps:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;
You are getting the type name of the textbox, which leads me to believe that your code rather looks something like:
sw.WriteLine(batedit);
I.e. you are sending the textbox object itself to be written to the file instead of the contents of its Text property. This will implicitly call the ToString method, which by default returns the type name of the object.
Also, you are not closing the StreamWriter properly, which might cause problems when you want to use it. You should call the Close method, and you don't have to call Flush before closing the StreamWriter. Alternatively you can put the StreamWriter in a using block, which would dispose it automatically, which will close it.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx#Y2863
The problem is simple: sw.writeline expects a string. You are sending it a text object which gets turned into the aformentioned .ToString(); which means your line gets translated, loosely, into
sw.WriteLine(theedit.ToString());
if you look at the documentation for WebControls.TextBox... scroll down the list to the Method ToString()
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx
What you need to do... is give it one string at a time (although I assume you could just give it the raw string from the textbox):
using System.IO;
namespace String_Writer
{
class Program
{
static void Main(string[] args)
{
string batname = "test.txt";
string theedit = "Testing one two three four\n\nfive six seven eight.";
using(StreamWriter sw = File.CreateText("C:\\Users\\Kriis\\Desktop\\" + batname))
{
using (StringReader reader = new StringReader(theedit))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
sw.WriteLine(line);
}
} while (line != null);
}
}
}
}
}
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);