Lines form a file deleting on start C# - c#

The problem im having is that everytime that i run my code, lines from the "Titles.txt" are getting deleted, and i don't know why. Basiclly, i run the program, then i write to the file with a textbox, then i close the program, check if it wrote to the file and it did, i run it again and check the file again and is empty. What can i do?
public Form1()
{
InitializeComponent();
if(!File.Exists(mainFolder))
{
Directory.CreateDirectory(mainFolder);
Directory.CreateDirectory(tabTitlesFolder);
var file = File.Create(tabTitles);
file.Close();
}
}

You need to check for the file, not the folder.
public Form1()
{
InitializeComponent();
if(!File.Exists(tabTitles)) // check if the file exists, (you had a check on mainFolder)
{
Directory.CreateDirectory(mainFolder);
Directory.CreateDirectory(tabTitlesFolder);
var file = File.Create(tabTitles); // this is what you are creating so also what you should be checking for above in the if
file.Close();
}
}
Also File.Create will overwrite the file if it already exists, see the documentation.
Finally types that implement IDisposable should be wrapped in a using block or a try/finally block to ensure they are released by the code even if an exception were to be thrown. File.Create returns FileStream which is disposable so it should be wrapped.
using(File.Create(tabTitles)){}
As you are not using the result you do not need to assign it to anything but you could if you wanted to write to the file.
using(var file = File.Create(tabTitles)){
// do something with file
}

File.Exists returns false for directories, hence you recreate the file on each run.

Related

System.IO.File.Delete throws "The process cannot access the file because it is being used by another process"

Every time I save a file and delete it right away using the function below, I keep getting this error message: "System.IO.IOException: The process cannot access the file because it is being used by another process".
Waiting for a couple of minutes or closing visual studio seems to only unlock the files that you uploaded previously.
public static bool DeleteFiles(List<String> paths)
{ // Returns true on success
try
{
foreach (var path in paths)
{
if (File.Exists(HostingEnvironment.MapPath("~") + path))
File.Delete(HostingEnvironment.MapPath("~") + path);
}
}
catch (Exception ex)
{
return false;
}
return true;
}
I think that the way I'm saving the files may cause them to be locked. This is the code for saving the file:
if (FileUploadCtrl.HasFile)
{
filePath = Server.MapPath("~") + "/Files/" + FileUploadCtrl.FileName;
FileUploadCtrl.SaveAs(filePath)
}
When looking for an answer I've seen someone say that you need to close the streamReader but from what I understand the SaveAs method closes and disposes automatically so I really have no idea whats causing this
After some testing, I found the problem. turns out I forgot about a function I made that was called every time I saved a media file. the function returned the duration of the file and used NAudio.Wave.WaveFileReader and NAudio.Wave.Mp3FileReader methods which I forgot to close after I called them
I fixed these issues by putting those methods inside of a using statement
Here is the working function:
public static int GetMediaFileDuration(string filePath)
{
filePath = HostingEnvironment.MapPath("~") + filePath;
if (Path.GetExtension(filePath) == ".wav")
using (WaveFileReader reader = new WaveFileReader(filePath))
return Convert.ToInt32(reader.TotalTime.TotalSeconds);
else if(Path.GetExtension(filePath) == ".mp3")
using (Mp3FileReader reader = new Mp3FileReader(filePath))
return Convert.ToInt32(reader.TotalTime.TotalSeconds);
return 0;
}
The moral of the story is, to check if you are opening the file anywhere else in your project
I think that the problem is not about streamReader in here.
When you run the program, your program runs in a specific folder. Basically, That folder is locked by your program. In that case, when you close the program, it will be unlocked.
To fix the issue, I would suggest to write/delete/update to different folder.
Another solution could be to check file readOnly attribute and change this attribute which explained in here
Last solution could be using different users. What I mean is that, if you create a file with different user which not admin, you can delete with Admin user. However, I would definitely not go with this solution cuz it is too tricky to manage different users if you are not advance windows user.

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);

what process is preventing my file from getting deleted in C#

I have a C# single thread application that creates a file. Uses that file and then deletes it. Some times the app has trouble deleting that file. The error I get is:
"The process cannot access the file --file path and file name-- because it is being used by another process."
How can I find out what process has a hold on this file and how can I make that process to let go so that the file can be deleted.
This thing rocks for that very "gotcha".
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
Process Monitor v3.05
It has a "Filter" submenu so you can fine tune it to the file that is locked.
You need to post the relevant code so we can see.
It is however always important to make sure that your app close the file that it has opened.
usually something like this will ensure that:
using(var f = File.OpenRead("myfile")) {
...
}
or the equivalent:
try {
var f = File.OpenRead("myfile");
} finally {
f.close()
}
Make sure that you are closing file before delete.
if you are using StreamWriter class make sure that you are closing with its variable
Ex. StreamWriter sw = new StreamWriter();
// some writing operation
sw.Close();

Deleting a temp file that is open c#

i have written some pdf files to a temp directory and these get displayed as a thumbnail that the user can view. when i close my form i clean up all of the files in the temp directory.
If however the user has one of the thumbnails open and then closes my application - it deletes the files and then throws an exception because the pdf is open in another process and cant be cleaned up.
I guess this is a shocking programming decision by me, but i am still a novice! How should i account for this in my code?
Thanks
You can detect if the file is in use by using code similar to below, then use that to warn the user that a file can't be deleted.
Unfortunately you can't delete a file that is in use.
public static bool IsFileInUse(string pathToFile)
{
if (!System.IO.File.Exists(pathToFile))
{
// File doesn't exist, so we know it's not in use.
return false;
}
bool inUse = false;
System.IO.FileStream fs;
try
{
fs = System.IO.File.Open(pathToFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.None);
fs.Close();
}
catch (System.IO.IOException ex)
{
string exMess = ex.Message;
inUse = true;
}
return inUse;
}
You should catch that exception (in catch block you can inform user to close that file or it will not be deleted), and if the temp directory is yours you can try to delete it when application starts (or when it ends again), if its windows temp directory, then it does not matter that much
Tools like File Unlocker can release a file. However I think this could make programs depending on the file crash...
Maybe you can look up how they unlock files or manage to execute the unlocker via Process.Start to unlock your file and delete it.
However if it's you blocking the file you should try and fix this in your programm. Maybe you should dispose all loaded files (filestreams etc) before trying to clean it up.

How to delete a file dynamically in c#?

while deleting a file dynamically using c# it couldn't be deleted because its being used
by another process but i have no other process which has been using this file.
foreach (string file in filess)
{
// FileInfo fi2 = new FileInfo(file);
// fi2.Delete();
File.Delete(file);
// ii = 0;
}
Generally if it say that it is used by another process then you should consider this as true. To have sure you can verify this with this tool: Process Explorer
It will tell you what process is locking file.
You should always make sure you close the streams you opened it:
using (FileStream stream = File.Create("C:\\1.txt"))
{
// your code goes here
}// the object will be closed here
because if you don't put this using block it will cause a lot of bugs even if you closed it manually with stream.Close();
If the File is in use you can't delete it, do the deletion in a try catch clauses. I would determine if the process using that file is your own app or some other process. You can use the Unlocker for that.
This is How you can delete simply
// File.Copy(#"‪C:\Users\Asus\Desktop\New.txt", #"D:\New.txt");
string rootFolder = #"D:\";
string authorsFile = "Gym.mdf";
File.Delete(Path.Combine(rootFolder, authorsFile));
string authorsFile2 = "Gym_log.ldf";
File.Delete(Path.Combine(rootFolder, authorsFile2));

Categories

Resources