Creating a file (.htm) in C# - c#

I would like to know the best way to create a simple html file using c#.
Is it using something like System.IO.File.Create?

Something like -
using (FileStream fs = new FileStream("test.htm", FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<H1>Hello</H1>");
}
}

I'll say that File.WriteAllText is a stupid-proof way to write a text file for C# >= 3.5.
File.WriteAllText("myfile.htm", #"<html><body>Hello World</body></html>");
I'll even say that File.WriteAllLines is stupid-proof enough to write bigger html without fighting too much with string composition. But the "good" version is only for C# 4.0 (a little worse version is C# >= 2.0)
List<string> lines = new List<string>();
lines.Add("<html>");
lines.Add("<body>");
lines.Add("Hello World");
lines.Add("</body>");
lines.Add("</html>");
File.WriteAllLines("myfile.htm", lines);
// With C# 3.5
File.WriteAllLines("myfile.htm", lines.ToArray());

I would go with File.Create and then open a StreamWriter to that file if you dont have all the data when you create the file.
This is a example from MS that may help you
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// Create the file.
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}

Have a look at the HtmlTextWriter class. For an example how to use this class, for example look at http://www.dotnetperls.com/htmltextwriter.

Reading and writing text files and MSDN info. HTML is just a simple text file with *.HTML extension ;)

Simply opening a file for writing (using File.OpenWrite() for example) will create the file if it does not yet exist.

If you have a look at http://msdn.microsoft.com/en-us/library/d62kzs03.aspx you can find an example of creating a file.
But how do you want to create the html file content? If that's just static then you can just write it to a file.. if you have to create the html on the fly you could use an ASPX file with the correct markup and use a Server.Execute to get the HTML as a string.

Yep, System.IO.File.Create(Path) will create your file just fine.
You can also use a filestream and write to it. Seems more handy to write a htm file

Related

Working with .tmp file for writing data

I'm wondering if there is a best practice when it comes to working with .tmp file for writing data. I like to make an .tmp that will be use in the filestream and then when I close the writer, I like to rename the file. Is there a way to rename file extension?
FileStream stream2 = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
StreamWriter streamWriter2 = new StreamWriter(stream2);
streamWriter2.WriteLine(textToAdd);
streamWriter2.Close();
string changed = Path.ChangeExtension(fileName, .txt);
File.Move(path, changed);
Here's how I would do this:
// Build a FileInfo object for your temp destination, this gives us
// access to a handful of useful file manipulation methods
var yourFile = new FileInfo(#"C:\temp\testfile.tmp");
// open a StreamWriter to write text to the file
using (StreamWriter sw = yourFile.CreateText())
{
// Write your text
sw.WriteLine("Test");
// There's no need to call Close() when you're using usings
}
// "Rename" the file -- this is the fastest way in C#
yourFile.MoveTo(#"C:\temp\testfile.txt");
You can use Path.GetFilenameWithoutExtension to remove the extension and then just add the one you want.

The process cannot access file due to opened already

The code running on wince 5.0 / .net framework compact 2.0
Always get a exception says:
the process cannot access the file because it is being used by another process.
Really confused as i already encolse the stream in the using statement,so the filestream should be closed automaticly once leave the using block .
//read text
using (StreamReader sr = File.OpenText(fname))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// append into stringbuilder
sb.Append(line);
sb.Append("\n");
}
}
//write text, below code raise the exception.
//if i comment it and re-run the code,exception disappear
using (StreamWriter sw = File.CreateText(fname))
{
sw.Write(sb.ToString());
}
addition:i just want to update the file, read and write. any better way?
sorry guys, the issue is in my code and i confused you here as i dont share that code.
actually because i wrote this in the very beginning of the program
// f is the fileinfo which point to fname as well
string text = f.OpenText().ReadToEnd();
this created a streamreader, not being assigned to any varible, but it's in the heap.so i ignored.
thanks people helpping here. BTW changed code to this then issue gone
using (StreamReader sr = f.OpenText())
{
string text = sr.ReadToEnd();
}
I tested this code on my computer. There is no problem.
Better way. For read and write full file, you can use File.ReadAllText(fname) and File.WriteAllText(fname). And instead of using \n use Environment.NewLine

StreamWriter is not able to write in file

My code is
System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File);
objStreamWriter.Write(txtEditor.Text);
objStreamWriter.Close();
txtEditor.Text = string.Empty;
I got a message The file has been modified out side of............. but my text file is empty. When in debug mode, I got a value of textEditor and path is not a problem. Am I missing some stupid things.
Thanks.
You have to verify the content of txtEditor before you write it to disk file.
string text=txtEditor.Text;
if(text.Trim.Length!=0)
{
using(System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File))
{
objStreamWriter.Write(text);
}
}
Use the StreamWriter by the "using" keyword for correct writing in to textfile.
using (StreamWriter writer = new StreamWriter("important.txt"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
}
Refer to the C# Using StreamWriter for more info

Create a temporary file from stream object in c#

Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore.
I thought of creating a class that implementing IDisposable and using it with the using code block in order to delete the temp file at the end.
Any idea of how to save the stream to a temp file and delete it on the end of use?
Thanks
You could use the TempFileCollection class:
using (var tempFiles = new TempFileCollection())
{
string file = tempFiles.AddExtension("xlsx");
// do something with the file here
}
What's nice about this is that even if an exception is thrown the temporary file is guaranteed to be removed thanks to the using block. By default this will generate the file into the temporary folder configured on the system but you could also specify a custom folder when invoking the TempFileCollection constructor.
You can get a temporary file name with Path.GetTempFileName(), create a FileStream to write to it and use Stream.CopyTo to copy all data from your input stream into the text file:
var stream = /* your stream */
var fileName = Path.GetTempFileName();
try
{
using (FileStream fs = File.OpenWrite(fileName))
{
stream.CopyTo(fs);
}
// Do whatever you want with the file here
}
finally
{
File.Delete(fileName);
}
Another approach here would be:
string fileName = "file.xslx";
int bufferSize = 4096;
var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose)
// now use that fileStream to save the xslx stream
This way the file will get removed after closing.
Edit:
If you don't need the stream to live too long (eg: only a single write operation or a single loop to write...), you can, as suggested, wrap this stream into a using block. With that you won't have to dispose it manually.
Code would be like:
string fileName = "file.xslx";
int bufferSize = 4096;
using(var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose))
{
// now use that fileStream to save the xslx stream
}
// Get a random temporary file name w/ path:
string tempFile = Path.GetTempFileName();
// Open a FileStream to write to the file:
using (Stream fileStream = File.OpenWrite(tempFile)) { ... }
// Delete the file when you're done:
File.Delete(tempFile);
EDIT:
Sorry, maybe it's just me, but I could have sworn that when you initially posted the question you didn't have all that detail about a class implementing IDisposable, etc... anyways, I'm not really sure what you're asking in your (edited?) question. But this question: Any idea of how to save the stream to temp file and delete it on the end of use? is pretty straight-forward. Any number of google results will come back for ".NET C# Stream to File" or such.
I just suggest for creating file use Path.GetTempFileName(). but others depends on your usage senario, for example if you want to create it in your temp creator class and use it just there, it's good to use using keyword.

How to append data to a binary file?

I have a binary file to which I want to append a chunk of data at the end of the file, how can I achieve this using C# and .net? Also is there anything to consider when writing to the end of a binary file? Thanks a lot for your help.
private static void AppendData(string filename, int intData, string stringData, byte[] lotsOfData)
{
using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None))
using (var bw = new BinaryWriter(fileStream))
{
bw.Write(intData);
bw.Write(stringData);
bw.Write(lotsOfData);
}
}
You should be able to do this via the Stream:
using (FileStream data = new FileStream(path, FileMode.Append))
{
data.Write(...);
}
As for considerations - the main one would be: does the underlying data format support append? Many don't, unless it is your own raw data, or text etc. A well-formed xml document doesn't support append (without considering the final end-element), for example. Nor will something like a Word document. Some do, however. So; is your data OK with this...
Using StreamWriter and referencing DotNetPerls, make sure to add the True boolean to the StreamWriter constructor, if otherwise left blank, it'll overwrite as usual:
using System.IO;
class Program
{
static void Main()
{
// 1: Write single line to new file
using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
{
writer.WriteLine("Important data line 1");
}
// 2: Append line to the file
using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
{
writer.WriteLine("Line 2");
}
}
}
Output
(File "log.txt" contains these lines.)
Important data line 1
Line 2
This is the solution that I was actually looking for when I got here from Google, although it wasn't a binary file though, hope it helps someone else.

Categories