views:

7948

answers:

5

Dear all, I've been working in this small piece of code that seems trivial but still i cannot really see where is the problem. My functions does a pretty simple thing. Opens a file, copy its contents, replace a string inside and copy it back to the original file (a simple search and replace inside a text file then). I didn't really know how to do that as I'm adding lines to the original file, so i just create a copy of the file, (file.temp) copy also a backup (file.temp) then delete the original file(file) and copy the file.temp to file. I get an exception while doing the delete of the file. Here is the sample code:

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
    {
        Boolean result = false;
        FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs);

        StreamReader streamreader = file.OpenText();
        String originalPath = file.FullName;
        string input = streamreader.ReadToEnd();
        Console.WriteLine("input : {0}", input);

        String tempString = input.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", tempString);

        try
        {
            sw.Write(tempString);
            sw.Flush();
            sw.Close();
            sw.Dispose();
            fs.Close();
            fs.Dispose();
            streamreader.Close();
            streamreader.Dispose();

            File.Copy(originalPath, originalPath + ".old", true);
            FileInfo newFile = new FileInfo(originalPath + ".tmp");
            File.Delete(originalPath);
            File.Copy(fs., originalPath, true);

            result = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        return result;
    }`

And the related exception

System.IO.IOException: The process cannot access the file 'E:\mypath\myFile.cs' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Delete(String path)
   at callingMethod.modifyFile(FileInfo file, String extractedMethod, String modifiedMethod)

Normally these errors come from unclosed file streams, but I've taken care of that. I guess I've forgotten an important step but cannot figure out where. Thank you very much for your help,

+2  A: 

The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.

chris.w.mclean
+1  A: 

It worked for me.

Here is my test code. Test run follows:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
 class Program
 {
  static void Main(string[] args)
  {
   FileInfo f = new FileInfo(args[0]);
   bool result = modifyFile(f, args[1],args[2]);
  }
  private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) 
  { 
   Boolean result = false; 
   FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); 
   StreamWriter sw = new StreamWriter(fs); 
   StreamReader streamreader = file.OpenText(); 
   String originalPath = file.FullName; 
   string input = streamreader.ReadToEnd(); 
   Console.WriteLine("input : {0}", input); 
   String tempString = input.Replace(extractedMethod, modifiedMethod); 
   Console.WriteLine("replaced String {0}", tempString); 
   try 
   { 
    sw.Write(tempString); 
    sw.Flush(); 
    sw.Close(); 
    sw.Dispose(); 
    fs.Close(); 
    fs.Dispose(); 
    streamreader.Close(); 
    streamreader.Dispose(); 
    File.Copy(originalPath, originalPath + ".old", true); 
    FileInfo newFile = new FileInfo(originalPath + ".tmp"); 
    File.Delete(originalPath); 
    File.Copy(originalPath + ".tmp", originalPath, true); 
    result = true; 
   } 
   catch (Exception ex) 
   { 
    Console.WriteLine(ex); 
   } 
   return result; 
  }
 }
}


C:\testarea>ConsoleApplication1.exe file.txt padding testing
input :         <style type="text/css">
  <!--
   #mytable {
    border-collapse: collapse;
    width: 300px;
   }
   #mytable th,
   #mytable td
   {
    border: 1px solid #000;
    padding: 3px;
   }
   #mytable tr.highlight {
    background-color: #eee;
   }
  //-->
  </style>
replaced String         <style type="text/css">
  <!--
   #mytable {
    border-collapse: collapse;
    width: 300px;
   }
   #mytable th,
   #mytable td
   {
    border: 1px solid #000;
    testing: 3px;
   }
   #mytable tr.highlight {
    background-color: #eee;
   }
  //-->
  </style>
Robert Harvey
A: 

Are you running a real-time antivirus scanner by any chance ? If so, you could try (temporarily) disabling it to see if that is what is accessing the file you are trying to delete. (Chris' suggestion to use Sysinternals process explorer is a good one).

Moe Sisko
+3  A: 

Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
    try
    {
        string contents = File.ReadAllText(file.FullName);
        Console.WriteLine("input : {0}", contents);
        contents = contents.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", contents);
        File.WriteAllText(file.FullName, contents);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }
}
Si
+1 the whole complex dispose close, flush streamreader thingy (not using using statement etc.. etc..) makes me shiver. its making a simple problem into a hugh unmaintainable mess.
Sam Saffron
Thank you very much for this method, i agree that it is much more clear this way than my original one.This solved my problem!
Srodriguez
+1  A: 

Hey guys, I realise that I is kinda late, but still better late than never. I was having simila problem recently. I used XMLWriter to subsequently update xml file and was recieving the same errors. I found the clean solution for this:

The XMLWriter uses underlaying FileStream to access the modified file. Problem is that when you call XMLWriter.close() method, the underlaying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlaying stream closed. example:

XMLWriterSettings settings = new Settings(); settings.CloseOutput = true; XMLWriter writer = new XMLWriter(filepath, settings);

Hope it helps

roquen