Reputation: 531
I try to create a file after checking if the directory exists, and if the file exists.
But When my program gets to this line I get the error that I can't create the file because it's already being used by another process. The weird thing is that it shouldn't. Even when the file doesn't exist.
File.Create(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile).Close()
the error occurs in this part of the code, catch not included. I know that I should have used Using() but This should work too. I don't fancy to redo this part that way untill it works this way.
if (!System.IO.Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\Channels"))
{
connection.Logger.Log("making " + System.IO.Directory.GetCurrentDirectory() + "\\Channels", false, LogMode.Info);
System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\Channels");
}
string saveFile = Program.RemoveForbiddenFileCharacters(this.ChannelName + ".Channel");
string saveFilePath = System.IO.Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile;
FileStream fileStream = null;
StreamWriter streamWriter = null;
try
{
if (File.Exists(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile))
{
File.Delete(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile);
}
File.Create(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile).Close();
streamWriter = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile);
//safe stuff to file
streamWriter.Close();
}
catch (Exception e)
Upvotes: 0
Views: 329
Reputation: 140
Nothing is wrong with the code you listed here and you need to provide more information for an answer.
I.e., I created a console application that consists of the following c# code and it executes without a problem and creates the file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string saveFile = "test.txt";
try
{
if (File.Exists(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile))
{
File.Delete(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile);
}
File.Create(Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile).Close();
StreamWriter streamWriter = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\Channels\\" + saveFile);
//safe stuff to file
streamWriter.Close();
}
catch (Exception ex)
{
}
}
}
}
Of course the file name had to be "hard coded" in, but you can see that the code is generally the same and if you copy it into a new console application you will also see that it works.
Upvotes: 1
Reputation: 22379
If you've just deleted the file, then the OS might prevent you from creating it within a few seconds because it's not completely done deleting it yet.
Why don't you just open the file for writing, instead of deleting and recreating it?
Upvotes: 0