Creating text file in C# - c#

I'm learning how to create text file in C# but I have a problem. I used this code:
private void btnCreate_Click(object sender, EventArgs e)
{
string path = #"C:\CSharpTestFolder\Test.txt";
if (!File.Exists(path))
{
File.Create(path);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The first line!");
}
}
else if (File.Exists(path))
MessageBox.Show("File with this path already exists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
When I press the "Create" button, Visual Studio shows an error 'System.IO.DirectoryNotFoundException', which points at "File.Create(path)".
Where is the problem?

Well supposing that your directory exists (as you have said) then you have another problem
File.Create keeps locked the file that it creates, you cannot use the StreamWriter in that way.
Instead you need to write
using(FileStream strm = File.Create(path))
using(StreamWriter sw = new StreamWriter(strm))
sw.WriteLine("The first line!");
however all this is not really necessary unless you need to create the file with particular options (see File.Create overload list) because StreamWriter creates the file itself if it doesn't exist.
// File.Create(path);
using(StreamWriter sw = new StreamWriter(path))
sw.WriteLine("Text");
...or all on one line
File.WriteAllText(path, "The first line");

The exception is indicating that your Directory C:\CSharpTestFolder doesn't exist. File.Create will create a file in existing folder/path, it will not create the full path as well.
Your check File.Exists(path) will return false, since the directory doesn't exists and so as the file. You need to check Directory.Exists on the folder first and then create your directory and then file.
Enclose your file operations in try/catch. You can't be 100% sure of File.Exists and Directory.Exists, there could be other process creating/removing the items and you could run into problems if you solely rely on these checks.
You can create Directory like:
string directoryName = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryName);
(You can call Directory.CreateDirectory without calling Directory.Exists, if the folder already exists it doesn't throw exception) and then check/create your file

You have to create the directory first.
string directory = #"C:\CSharpTestFolder";
if(!Directory.Exists(directory))
Directory.CreateDirectory(directory);
string path = Path.Combine(directory, "Test.txt");
if (!File.Exists(path))
{
File.Create(path);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The first line!");
}
}
else if (File.Exists(path))
MessageBox.Show("File with this path already exists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

Try this.
string path = #"C:\CSharpTestFolder";
if (Directory.Exists(path))
{
File.AppendAllText(path + "\\Test.txt", "The first line");
}
else
{
Directory.CreateDirectory(path);
File.AppendAllText(path + "\\Test.txt", "The first line");
}
The File.AppendAllText(path, text) method will create a text file if it does not exist; append the text and will close the file.
If the file already exists, it will open the file and append the text to it and then close the file.
The exception shows that the directory C:\CSharpTestFolder does not exist.

Related

C# move file with 2 mapped drives

I need to move a file existing on a mapped folder named A:\ to another mapped folder B:\ using the code below
File.Move(#"A:\file.txt",#"B:\");
it return the error below
Could not find file 'A:\file.txt'.
i tried to open A:\file.txt in folder explorer and it open the file normally
It looks like File.Move only works for files on local drives.
File.Move actually invokes MoveFile which states that both source and destination should be:
The current name of the file or directory on the local computer.
You would be better by using a combination of File.Copy and File.Delete.
Copy the file from A to B, then delete the file from A.
As stated before, File.Move needs sourceFileName and destFileName.
And you are missing the Filename in the second parameter.
If you want to move you file and keep the same name you can Extract the File name from the sourceFileName with GetFileName and use it in your destFileName
string sourceFileName = #"V:\Nothing.txt";
string destPath = #"T:\";
var fileName = Path.GetFileName(sourceFileName);
File.Move(sourceFileName, destPath + fileName );
Here is a debug code:
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
Console.WriteLine("The original file does not exists, let's Create it.");
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2)) {
Console.WriteLine("The target file already exists, let's Delete it.");
File.Delete(path2);
}
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}

Creating a Txt-File and write to it [duplicate]

This question already has answers here:
C# exception. File is being used by another process
(7 answers)
Closed 5 years ago.
I want to create a text file then add the text of a TextBox to it.
Creating the text file works without any problems with following code:
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
File.Create(path);
}
But I get an error that the file is being used when I try to add the text to the text file. If the file already exist before it run the code I don't get this error and the TextBox.Text is added to the File.
I use this code to add the text to the text file:
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
}
Can you help me?
You don't actually have to check if the file exists, as StreamWriter will do that for you.
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
public StreamWriter(
string path,
bool append
)
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
You should use File.Create with using statement as it's locking the file on creating.So just change this line :
File.Create(path);
To this:
using (File.Create(path));
As you can see here, StreamWriter will actually create a file on specified path when it doesn't exist so it's useless to check for it.
I would suggest to remove the part which is creating the file and simply just start writing :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
tw.Close();
}
}
But if you really want to create the file beforehand, remember to Dispose FileStream object created by File.Create call. Dispose call will automatically call Flush and Close for you so it's safe enough and you can do this in many ways like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
using ( File.Create(path) ) ; // This will generate warnings that you're not using the object and so on, but that's okay,
}
Or like this :
InitializeComponent();
string path = #"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Dispose();
}
If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. So you don't need to check if the file exists or not.
You need to make sure the file is closed before you want to modify it.
You need to Move your
tw.Close();
Outside your using. Like so :
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
tw.Close();
}
}
Edit : As pointed out, when the using ends the writer is disposed, so does not need manually closing.
public void writeTxt()
{
string path = #"C:\Users\Morris\Desktop\test.txt";
if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}
}
}
This problem has been answered before in this thread.
Closing a file after File.Create
You will need to close the stream to the file before using it again.

Writting text to file c#.it's being used by another process

I am creating a text file and after that I am trying to write some text in that file.but when writing text,it's generating exception that process cannot access file because it's being used by another process. Kindly someone help :( Thanks in advance.
Here is my code
dt_Loc = loc1_ctab.GetEmpLocInfo(Session["empcd"].ToString());
string str = DateTime.Now.ToString("dd-mmm-yyyy");
str = dt_Loc.Rows[0]["loc1_abrv"].ToString() + "-" + str;
string path = FilesPath.Path_SaveFile + str + ".txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txt_comments.Text);
tw.Close();
}
Remove the File.Create since it opens a FileStream for the file.This results in the file being open and hence you get the exception that the file is being used by another process.
if (!File.Exists(path))
{
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(txt_comments.Text);
}
}
Your code giving such error because, the method Create Creates or overwrites a file in the specified path. which will return A FileStream that provides read/write access to the file specified in path. So at the time of executing the writemethod, the file is being used by the returned FS. you can use this in the following way:
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes(txt_comments.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can Make it simple by using File.WriteAllText which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
string path =FilesPath.Path_SaveFile + str + ".txt";;
if (!File.Exists(path))
{
File.WriteAllText(path, txt_comments.Text);
}

Can't get overwrite to work during File.Copy - unable to access error

I have been looking all at kinds of solutions for allowing an overwrite to occur from the following error
{"The process cannot access the file
'C:\pathway\filename.txt' because it is being
used by another process."}
I have tried, flushing, closing, GC.Collect(), ect... but I cannot seem to find a way pass this error.
I write a "temp" file as such
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (var line in detailLines)
{
sw.WriteLine(line);
}
sw.Flush();
sw.Close();
}
}
GC.Collect();
Then allow the user to specify their own destination where I copy the file above, to.
private void SaveFile()
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.FileName = fileName;
saveFile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (saveFile.ShowDialog() == DialogResult.OK)
{
System.IO.File.Copy(fileName, saveFile.FileName, true);
}
}
I can save as a new name fine, but if I attempt to save at the same pathway and name as the "temp" file, then it asks "if I want to replace this file" and after I click yes it crashes and throws that cannot access error.
Can someone explain how I can access and overwrite a file in the same destination?
Despite the fact that File.Copy method says that:
Overwriting a file of the same name is allowed.
It actually fails to succeed in it(looks like something else has been meant by this sentence):
try
{
String filePath = #"C:\TEMP\test.txt";
using (var fs = new StreamWriter(filePath))
{
fs.Write("data");
}
Console.WriteLine("File written");
// Fails
System.IO.File.Copy(filePath, filePath, true);
Console.WriteLine("File overwritten by itself");
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
So, you should probably just check whether the temp file and target file are the same and act accordingly:
if (fileName != saveFile.FileName)
System.IO.File.Copy(fileName, saveFile.FileName, true);
P.S.: There is always some probability of race conditions in the file system, but I don't think that you should really worry about it - dealing with it will just make your code more complex and improve nothing.

"File in use" error when writing to text file

I'm getting the error The process cannot access the file 'C:\Users\Ryan\Desktop\New folder\POSData.txt' because it is being used by another process. when I try to create a file and then write to it. What process is using the file?? I checked for a file.close to call after I create the file, but it doesn't exist. How do I get past this? Thanks!
Heres my code:
MessageBox.Show("Please select a folder to save your database to.");
this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
DialogResult result = this.folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
if (!File.Exists(databasePath + "\\POSData.txt"))
{
File.Create(databasePath + "\\POSData.txt");
}
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Edit: Only happens when creating the file. If it already exists, no error occurs.
Actually, don't even bother using File.Create. The reason you're getting that error is because File.Create is opening up a stream on that text file.
string filePath = "databasePath + "\\POSData.txt"";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
You are keeping the file open when you call File.Create (i.e. you never close the file).
StreamWriter will create the file for you if it doesn't exist, so I wouldn't bother checking yourself. You could just remove the code that checks whether it exists and creates it if it doesn't.
if (result == DialogResult.OK)
{
databasePath = folderBrowserDialog1.SelectedPath;
using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
{
w.WriteLine(stockCount);
}
}
Note that if the file doesn't exist, the second bool parameter in the StreamWriter constructor is ignored.
File.Create also opens the file for reading/writing. As such, you're leaving an open FileStream when you File.Create.
Assuming that overwriting is OK, then you probably want to do something like this:
using (var fs = File.Create(databasePath + "\\POSData.txt"))
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine(stockCount);
}
given that File.Create:
Creates or overwrites a file in the specified path.
The File.Create returns a FileStream object that might need to be closed.
The FileStream object created by this method has a default FileShare
value of None; no other process or code can access the created file
until the original file handle is closed.
using (FileStream fs = File.Create(databasePath + "\\POSData.txt"))
{
fs.Write(uniEncoding.GetBytes(stockCount), 0, uniEncoding.GetByteCount(stockCount));
}
I used this and it worked
`File.AppendAllText(fileName,"");`
This creates a new file, writes nothing to it, then closes it for you.

Categories