0

Don't Know What's wrong but I can't Access even It created a directory.. This is my code

private void btnRegister_Click(object sender, EventArgs e)
{
    try
    {
        var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID");
        sw.Write(txtAcc.Text + "\n" + txtZipCode.Text);
        sw.Close();
    }
    catch(System.IO.DirectoryNotFoundException ex)
    {
        System.IO.Directory.CreateDirectory("E:Praisey\\" + txtAcc.Text + "\\Login.ID");
        var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID");
        sw.Write(txtAcc.Text + "\n" + txtZipCode.Text);
        sw.Close();
    }
}

it always getting error! The error is

UnauthorizedAccessException was unhandled

Access to the path 'E:\Praisey\48492995\Login.ID' is denied.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 2
    Possible duplicate http://stackoverflow.com/questions/8821410/why-is-access-to-the-path-denied – Arash Oct 01 '15 at 09:22
  • well, maybe you are running with permissions that don't have access to that directory/file? – Icepickle Oct 01 '15 at 09:24
  • You are creating `"E:Praisey\\" + txtAcc.Text + "\\Login.ID"` directory and then creating `StreamWriter` to the same path... Also, you might not have access to `E:\Praisey` directory. Which line exactly throws the exception? – tdragon Oct 01 '15 at 09:26
  • @tdragon in var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID"); – AlgorithNewbie Oct 01 '15 at 09:29

2 Answers2

0

This error occurs (had it yesterday too) when the Directory does not exist. You need to create it before starting your StreamWriter.

if (!Directory.Exists("E:Praisey\\" + txtAcc.Text))
    Directory.CreateDirectory("E:Praisey\\" + txtAcc.Text);
kevintjuh93
  • 1,010
  • 7
  • 22
0

As I see from your catch block, "E:Praisey\\" + txtAcc.Text + "\\Login.ID" is actually a directory. You must also add the file name to the path.

var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID\\filename.txt");