Jogi
Jogi

Reputation: 1

Access to the path 'C:\Users\mehdi\Desktop\sample\Test' is denied

I'm trying to load a folder into a winForm app. App should read the files in the folder and perform some operation on the files. Following is the implementation:

private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
        DialogResult result = folderBrowserDialog.ShowDialog();

        var files = from file in Directory.EnumerateFiles(folderBrowserDialog.SelectedPath, "*.chunk*", SearchOption.AllDirectories)
                    from line in File.ReadLines(file)
                    select new
                    {
                        File = file,
                        Line = line
                    };
        string newPath = folderBrowserDialog.SelectedPath;
        if (!Directory.Exists(newPath))
        {
            System.IO.Directory.CreateDirectory(newPath + @"\Test");
        }

        foreach (var f in files)
        {

            string path = f.File.ToString();
            string filename = Path.GetFileName(path);
            string s = string.Empty;
            using (StreamReader reader = new StreamReader(path, true))
            {
                s = reader.ReadToEnd();
                reader.Close();
            }

            string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            using (File.CreateText(Path.Combine(newPath + @"\Test", filename+".txt")))
            { }
            using (StreamWriter sw = File.CreateText(Path.Combine(newPath + @"\Test", filename + ".txt")))
            {
                string output = string.Empty;
                foreach (string st in parts)
                {
                    output += st + ",";
                }
                sw.Write(output);
            }
        }
    }

There is an error on line using (File.CreateText(newPath)) saying:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

Additional information: Access to the path 'C:\Users\mehdi\Desktop\sample\Test' is denied.

What I'm trying to do is, App should load the folder and read each text file and perform the given task (replace out-of-sequence white space between the words with comma) and then save each file in the new folder created as System.IO.Directory.CreateDirectory(newPath);. All is happening as expected but when operation reaches to writing files to newly created folder Test, it is not allowing it the access.

Any ideas where I'm going wrong?

Upvotes: 1

Views: 2276

Answers (1)

vendettamit
vendettamit

Reputation: 14677

You're using Directory path in newPath to create a file. Append the file name in newPath to create a file.

File.CreateText(Path.Combine(newPath, "<yourfileName>.extension"))

Upvotes: 4

Related Questions