Solved

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

Posted on 2014-10-17
8
1,870 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
This video teaches viewers about errors in exception handling.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

860 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