-2

I am checking file is present if specified location and if so I am replacing single quote by &#39. For this I am using WriteAllText method. For my knowledge WriteAllText will be used to Create file and write the text and close it, target file is already exists, it will be overwritten.

I don't know why I am getting System.IOException while using

var file = AppDomain.CurrentDomain.BaseDirectory + "test";
if (Directory.Exists(file))
{
    string text = File.ReadAllText(file + "\\test.txt");
    text = text.Replace("'", "&#39");
    File.WriteAllText(file + "\\test.txt", text);
}

Note: I am using this inside Application_BeginRequest method.

Suggest me how to avoid this exception ?

Shesha
  • 1,857
  • 6
  • 21
  • 28

2 Answers2

0

Use your code like below

            var file = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
            if (File.Exists(file))
            {
                string text = File.ReadAllText(file);
                text = text.Replace("'", "&#39");
                File.WriteAllText(file, text);
            }

Hope this will solve your problem

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
0

Firstly, You are asking on existence of Directory while using

Directory.Exists(file)

In order to check existence of File you need to use

File.Exists(file)

Secondly, You are trying to ReadAllText from the file by passing as parameter the file concatenated with the file name again. So the file name you are passing is actually:

AppDomain.CurrentDomain.BaseDirectory + "test.txt" + "\\test.txt";

Thirdly, same comment for WriteAllText as for ReadAllText.

There are a lot of examples on the net to learn how to read and write from a file, for example:

Read from a Text File - MSDN
Write to a Text File - MSDN

ehh
  • 3,412
  • 7
  • 43
  • 91
  • You should give meaningful names to your variables. Do not call file to a variable that represents a directory. Call if directoryPath or folderPath for example. After fixing that, do you still have issues? – ehh Apr 13 '16 at 06:14
  • I have added a condition to check if file has single quotes. if (text.Contains("'")). Now I am not getting the exception. – Shesha Apr 13 '16 at 06:17