Solved

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

Posted on 2014-10-17
8
2,127 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 34

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 34

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 34

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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilationā€¦
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a feā€¦
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

688 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