Solved

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

Posted on 2014-10-17
8
1,785 Views
Last Modified: 2015-02-17
I'm having to maintain a C# program that is using File.WriteAllLines to write a file to disk.  I've needed to create at temp file to read back in and change some data based on data in another file read in.  

I want to delete the temp file when I leave so the user won't have the intermediate file to get confused with, but I get an error: "The process cannot access the file ... because it is being used by another process."

How do I "free" this intermediate file?  I don't see a Close method on File and nothing that I can find that sends back a handle that I could use to free or close that file I've written.

Thanks,
-- Jim Lowary
0
Comment
Question by:farminsure
  • 4
  • 3
8 Comments
 
LVL 33

Expert Comment

by:it_saige
ID: 40386693
What code are you using to manipulate the file (open, write, etc.)???  Is this file exclusive to this program only???

-saige-
0
 
LVL 16

Expert Comment

by:George Tokas
ID: 40386707
Check out the following from MS:
http://msdn.microsoft.com/en-us/library/b9skfh7s(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
It is for open() function but there are examples of the same functionality in C# and C++.
You will see that in C++ is using delete to free the file and in C# only the keyword using is needed to release the filestream object after finishing.
You can use a similar method.

George Tokas.
0
 

Author Comment

by:farminsure
ID: 40386767
Yes, the file is exclusive to this program.
The code I have File.WriteAllLines build the file

then to read it:

      public CSVReader(string filename, Encoding enc)
            : this(new FileStream(filename, FileMode.Open), enc) { }

        public string[] GetCSVLine()
        {
            string data = reader.ReadLine();
            if (data == null) return null;
            if (data.Length == 0) return new string[0];

            ArrayList result = new ArrayList();

            ParseCSVFields(result, data);      // puts the csv file into result array

            return (string[])result.ToArray(typeof(string));
        }
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 33

Expert Comment

by:it_saige
ID: 40387598
I don't seem to have any problems reading back from a File.WriteAllLines().  There may be more that we are not seeing.

Here is the example code that I used:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FileExample
{
	class Program
	{
		static void Main(string[] args)
		{
			List<string> writer = new List<string>()
			{
				"1,2,3,4,5,6,7,8,9,10",
				"a,b,c,d,e,f,g,h,i,j",
				"10,9,8,7,6,5,4,3,2,1",
				"j,i,h,g,f,e,d,c,b,a"
			};
			File.WriteAllLines(@"c:\writealllines.txt", writer.ToArray());
			CSVReader readback = new CSVReader(@"c:\writealllines.txt", Encoding.ASCII);
			var Data = readback.GetCSVLines();
			foreach (var item in Data)
			{
				string line = string.Empty;
				foreach (var element in item)
					line += string.Format(" [{0}] ", element);
				Console.WriteLine(line);
			}
			Console.ReadLine();
		}
	}

	class CSVReader
	{
		FileInfo _file = null;
		Encoding _encoding = Encoding.Default;

		public CSVReader(string file, Encoding enc) : this(new FileInfo(file), enc) { ;}

		public CSVReader(FileInfo file, Encoding enc) { _file = file; }

		public IEnumerable<string[]> GetCSVLines()
		{
			if (_file.Exists)
			{
				string[] lines = File.ReadAllLines(_file.FullName, _encoding);
				if (lines.Length > 0)
				{
					foreach (string line in lines)
						yield return ParseCSVFields(line);
				}
			}
		}

		public string[] ParseCSVFields(string data)
		{
			return data.Split(',');
		}
	}
}

Open in new window


Produced the following output:Capture.JPG
With the following file created:Capture.JPG
-saige-
0
 

Author Comment

by:farminsure
ID: 40397709
I can read it back just fine the problem becomes when I close the program I want to delete the file and it give me the message;  "The process cannot access the file ... because it is being used by another process."

I was looking for a way of doing this with out totally redoing the program.
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40397944
There are a couple of reasons why you may not be able to delete the file.  Either, your FileStream still has the file open (you can get rid of this problem by way of a using statement) or because you don't have security access to the file (possible but highly unlikely as you created the file on the fly).

Amended above to include a File.Delete() -
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FileExample
{
	class Program
	{
		static void Main(string[] args)
		{
			List<string> writer = new List<string>()
			{
				"1,2,3,4,5,6,7,8,9,10",
				"a,b,c,d,e,f,g,h,i,j",
				"10,9,8,7,6,5,4,3,2,1",
				"j,i,h,g,f,e,d,c,b,a"
			};
			File.WriteAllLines(@"c:\writealllines.txt", writer.ToArray());
			CSVReader readback = new CSVReader(@"c:\writealllines.txt", Encoding.ASCII);
			var Data = readback.GetCSVLines();
			foreach (var item in Data)
			{
				string line = string.Empty;
				foreach (var element in item)
					line += string.Format(" [{0}] ", element);
				Console.WriteLine(line);
			}
			File.Delete(@"c:\writealllines.txt");
			Console.WriteLine(string.Format("The file I just created and reread exists? {0}", File.Exists(@"c:\writealllines.txt")));
			Console.ReadLine();
		}
	}

	class CSVReader
	{
		FileInfo _file = null;
		Encoding _encoding = Encoding.Default;

		public CSVReader(string file, Encoding enc) : this(new FileInfo(file), enc) { ;}

		public CSVReader(FileInfo file, Encoding enc) { _file = file; }

		public IEnumerable<string[]> GetCSVLines()
		{
			if (_file.Exists)
			{
				string[] lines = File.ReadAllLines(_file.FullName, _encoding);
				if (lines.Length > 0)
				{
					foreach (string line in lines)
						yield return ParseCSVFields(line);
				}
			}
		}

		public string[] ParseCSVFields(string data)
		{
			return data.Split(',');
		}
	}
}

Open in new window

Produces the following output -Capture.JPG
-saige-
0
 

Accepted Solution

by:
farminsure earned 0 total points
ID: 40606092
I just used a different file name a went on with project.  Did not have time to research further or do any rewrites.
Thanks for all suggestions.
0
 

Author Closing Comment

by:farminsure
ID: 40613804
Wasn't what I wanted but was what I had time to do.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Advice in Xamarin 21 78
Facial recognition to look through the whole database for a person 3 61
.NET 2008 VB and C# 6 27
transaction in asp.net, sql server 6 30
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

815 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now