Create text file in asp.net using code - c#

How do I create a text file using ASP.Net? I tried using Streamwriter but it only writes to exist file:
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), false))
{
_testData.WriteLine(txtText.Text); // Write the file.
_testData.WriteLine(txtLink.Text); // Write the file.
}
So how do I create it. I have tried:
FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]]);
but it did not work.

string FilePath = Server.MapPath("FILENAME.txt");
string FileContent = "Put File Content Here";
File.WriteAllText(FilePath, FileContent);

The constructor creates the file for you if it doesn't exist, so you shouldn't have to change anything. Just be aware that specifying "false" in the constructor will overwrite the file each time this code is executed.
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.
https://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx

Related

Appendtext not working

So I'm trying to make a program that calculates and saves your BMI into a file.
I tried using appendtext like this.
StreamWriter logboekBMI = new StreamWriter(path + "Logbmi.txt");
logboekBSA.Close();
logboekBMI = File.AppendText(path + "Logbmi.txt");
logboekBMI.WriteLine("BMI: " + bmi.getBMI());
logboekBMI.Close();
And I read the file to a text box like this:
StreamReader logbmi = new StreamReader(path + "Logbmi.txt");
txtLogboek.Text = logbmi.ReadToEnd();
It deletes the line that was already in the file and inserts the new one. It never appends.
If I understand the question correctly, you want to write text to a file without overwriting any text that is already there.
In that case, you need to define your StreamWriter like so:
StreamWriter logboekBMI = new StreamWriter(path + "Logbmi.txt", true);
The true parameter means that you want to append text to the file. Without it, you are overwriting the file every time you create a new StreamWriter.
Your code seems over complicated for what you want to do. You only need two lines of code, one to save the text and one to read it.
Save text: File.AppendAllText
Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
File.AppendAllText("C:\path\to\file\Logbmi.txt", "The BMI to add");
Read text: File.ReadAllText
Opens a text file, reads all lines of the file into a string, and then closes the file.
txtLogboek.Text = File.ReadAllText("C:\path\to\file\Logbmi.txt");

Creating File and copy data raising error

I am using C# in Microsoft Visual Studio 2012, I am working on the following code:
string source = "d:\\source.txt";
string newFile = "d:\\newFile.txt";
if(!File.Exists(newFile))
{
File.Create(newFile);
string content = File.ReadAllText(source);
File.AppendAllText(newFile,content);
}
This code successfully creates the File but when it compiles the File.AppendAllText(newFile,content) it generates the error:
the process cannot access the file "d:\newFile.txt" because it is being used by another process.
Why would this be?
The File.Create method returns a FileStream object. This is holding the file open for write. Until that object is closed the file cannot be written to. The best way to fix this is to simply close the returned file
File.Create(newFile).Close();
This code is essentially copying the contents of an existing file to a new one. There is already an API available that does exactly that: File.Copy. Your code could be simplified to the following
try {
File.Copy(source, newFile);
} catch (Exception) {
// File already exists or write can't occur
}
you don't need to create file , AppendAllText create if not exist, you get exception because File.Create return open file stream and then you try to access same file again. you need to properly close that stream before access the same file.
string source = "d:\\source.txt";
string newFile = "d:\\newFile.txt";
if(!File.Exists(newFile))
{
File.AppendAllText(newFile,File.ReadAllText(source););
}
File.AppendAllText:
Opens a file, appends the specified string to the file, and then
closes the file. If the file does not exist, this method creates a
file, writes the specified string to the file, then closes the file.
but you can simply do your task by one line
File.Copy(source , newFile , false);

Details about StreamWriter

Does StreamWriter or StreamReader auto creates the file when is using like below?
StreamWriter write = new StreamWriter("foo");
Yes, it creates the file if it doesn't exist, as per the documentation for this constructor:
The path parameter can be a file name, including a file on a Universal
Naming Convention (UNC) share. If the file exists, it is overwritten;
otherwise, a new file is created.
Certain forms of the constructor can overwrite, append, or create a new file yes. Read http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx for more details.

zipping with c#

i am trying to use GZipStream to create a gz file using c#.
my problem is that i have a list that contains strings. and i need to create a password protected zip file, and put in it a text file containing the strings.
i don't want to create the textfile, then zip it, and then delete the textfile. i want to directly create a password protected zip file that contains the text file.
any help?
EDIT: i am done with the zipping stuff. now i need to set a pass for the created zip file. any help?
You should consider using SharpZipLib. It's an open source .net compression library. It includes examples on how to create either a .gz or a .zip file. Note that you can write directly to the .zip file. You don't need to create an intermediate file on disk first.
Edit: (in response to your edit) SharpZipLib supports zip passwords too.
Just create a StreamWriter wrapping your GZipStream, and write text to it.
GZipStream can be used to create a .gz file, but this is not the same as a .zip file.
For creating password-protected zip files, I think you need to go to a third-party library.
Here's how to do it using DotNetZip...
var sb = new System.Text.StringBuilder();
sb.Append("This is the text file...");
foreach (var item in listOfStrings)
sb.Append(item);
// sb now contains all the content that will be placed into
// the text file entry inside the zip.
using (var zip = new Ionic.Zip.ZipFile())
{
// set the password on the zip (implicitly enables encryption)
zip.Password = "Whatever.You.Like!!";
// optional: select strong encryption
zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
// add an entry to the zip, specify a name, specify string content
zip.AddEntry("NameOfFile.txt", sb.ToString());
// save the file
zip.Save("MyFile.zip");
}

Write string to text file and ensure it always overwrites the existing content.

I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.
System.IO.File.WriteAllText (#"D:\path.txt", contents);
If the file exists, this overwrites it.
If the file does not exist, this creates it.
Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.
Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.
Generally, FileMode.Create is what you're looking for.
Use the file mode enum to change the File.Open behavior. This works for binary content as well as text.
Since FileMode.Open and FileMode.OpenOrCreate load the existing content to the file stream, if you want to replace the file completely you need to first clear the existing content, if any, before writing to the stream. FileMode.Truncate performs this step automatically
// OriginalFile:
oooooooooooooooooooooooooooooo
// NewFile:
----------------
// Write to file stream with FileMode.Open:
----------------oooooooooooooo
var exists = File.Exists(path);
var fileMode = exists
? FileMode.Truncate // overwrites all of the content of an existing file
: FileMode.CreateNew // creates a new file
using (var destinationStream = File.Open(path, fileMode)
{
await newContentStream.CopyToAsync(destinationStream);
}
FileMode Enum
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.

Categories

Resources