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));
Related
I'm using ZipFile.Open() to create an archive, then adding entries using CreateEntryFromFile(). The resulting file is invalid according to Windows. 7-zip can open the file, but only part of the files are listed.
The code looks like this:
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
while (reader.Read())
{
object myValue = reader.GetValue(0);
string objectId = myValue.ToString();
string objectPath = Path.Combine(myPath, objectId);
string[] files = Directory.GetFiles(objectPath);
if (files.Length > 0)
{
archive.CreateEntryFromFile(files[0], Path.GetFileName(files[0]));
}
}
}
As you can see, I do dispose of the ZipArchive when I'm done, and unlike every other question about this problem, I don't use any streams, so there's nothing to flush.
Anyone know what's wrong?
It could be possible that the file being added to the archive is being used by another process and cannot be accessed. To avoid this, you can try wrapping the CreateEntryFromFile method in a try-catch block and handle the IOException that could be thrown if the file is in use. You can also try closing any streams or file handles that may have been opened on the file before adding it to the archive.
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.
I've got this code
string archiveFileName = BuildArchiveFileName(i, null);
string tmpArchiveFileName = BuildArchiveFileName(i, "tmp");
try
{
using (FileStream tmpArchiveMemoryStream = new FileStream(tmpArchiveFileName, FileMode.Create))
{
using (BinaryWriter pakWriter = new BinaryWriter(tmpArchiveMemoryStream))
{
if (i == 0)
{
WriteHeader(pakWriter, pakInfo.Header);
WriteFileInfo(pakWriter, pakInfo.FileList);
uint remainingBytesToDataOffset = pakInfo.Header.DataSectionOffset - CalculateHeaderBlockSize(pakInfo.Header);
pakWriter.Write(Util.CreatePaddingByteArray((int)remainingBytesToDataOffset));
}
foreach (String file in pakInfo.FileList.Keys)
{
DosPak.Model.FileInfo info = pakInfo.FileList[file];
if (info.IndexArchiveFile == i)
{
//Console.WriteLine("Writing " + file);
byte[] fileData = GetFileAsStream(file, false);
int paddingSize = (int)CalculateFullByteBlockSize((uint)fileData.Length) - fileData.Length;
pakWriter.Write(fileData);
pakWriter.Write(Util.CreatePaddingByteArray(paddingSize));
}
}
}
}
}
finally
{
File.Delete(archiveFileName);
File.Move(tmpArchiveFileName, archiveFileName);
}
I've tested this with NUnit on small file sizes and it works perfectly. Then when I tried it on a real life example , that are files over 1 GB. I get in trouble on the delete. It states the file is still in use by another process. While it shouldn't that file should have been disposed of after exiting the using branch. So I'm wondering if the dispose of the filestream is slow to execute and that is the reason I'm getting in trouble. Small note in all my file handling I use a FileStream with the using keyword.
While it shouldn't that file should have been disposed of after exiting the using branch
That's not what it is complaining about, you can't delete archiveFileName. Some other process has the file opened, just as the exception message says. If you have no idea what process that might be then start killing them off one-by-one with Task Manager's Processes tab. That being your own process is not entirely unusual btw. Best way is with SysInternals' Handle utility, it can show you the process name.
Deleting files is in general a perilous adventure on a multi-tasking operating system, always non-zero odds that some other process is interested in the file as well. They ought to open the file with FileShare.Delete but that's often overlooked.
The safest way to do this is with File.Replace(). The 3rd argument, the backup filename, is crucial, it allows the file to be renamed and continue to exist so that other process can continue to use it. You should try to delete that backup file at the start of your code. If that doesn't succeed then File.Replace() cannot work either. But do check that it isn't a bug in your program first, run the Handle utility.
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();
I am getting the "The process cannot the file X because it is being used by another process" when I execute the following piece of code in my console application:
List<string> lines1 = new List<string>();
List<string> lines2 = new List<string>();
string path1 = ConfigurationManager.AppSettings.Get("path1");
string path2 = ConfigurationManager.AppSettings.Get("path2");
File.Create(path1);
File.Create(path2);
foreach (object myObject in myObjects)
{
//do some fancy logic here!!!
}
File.WriteAllLines(path1, lines1.ToArray()); //exception is thrown here
File.WriteAllLines(path2, lines2.ToArray());
How can I resolve this issue?
The likely problem here is the File.Create method. It's creating and returning a handle to the file in question wrapped in a FileStream object. That object is holding the file open for write and is hence blocking your later File.WriteAllLines call.
The simplest solution is to remove the File.Create calls. Just let the WriteAllLines method create the file for you
You have two options: File.Create not only creates the file but OPENS it. so you need to keep a reference to the filestream and close it like this:
var file1 = File.Create(path1);
var file2 = File.Create(path2);
file1.Close();
file2.Close();
OR you can just skip that because File.WriteAllLines(...) will create a file if it doesn't already exist.
You probably want to leverage something like File.Exist to prevent other exceptions, but that is not part of the present question.
File.Create(path1) is opening and keeping the file open and hence locking it.
File.WriteAllLines will create the file , so there is no need to create it first.
If you need to create it first (eg to test the path) you can do
FileStream fs = File.Create(path1);
fs.Close();
As per my comment above, File.Create(..) returns a FileStream object, which won't be destroyed until the method is closed (which means the handle is still open, thus file is still locked). When you're trying to use WriteAllLines it's attempting to open a new handle, and failing because one's already open.
You can use code like the following, which works fine (just tested):
List<string> lines1 = new List<string>();
string path1 = #"C:\Development\test1.txt";
for (int i = 0; i < 20; i++)
lines1.Add("Test " + i);
TextWriter textWriter = new StreamWriter(File.Create(path1));
foreach(string line in lines1)
textWriter.WriteLine(line);
textWriter.Close();
The code above will utilise the same stream that was created when the file was created, so you have no chance of collision.
Alternatively as in other answers, the File.WriteAllLines method will create the file for you anyway!
If you delete the File.Create lines, you should be fine. Unless you're doing something with the files in your foreach loop, you don't need to call the File.Create methods at all. The File.WriteAllLines will create a file if it doesn't exist. Since the File.WriteAllLines method also closes the filestream, you don't have to worry about managing the filestream returned by a File.Create.