Search code examples
c#asp.netfileaccess-denieddelete-file

Getting access denied when try to delete file


I'm getting access denied whenever I try to delete a file after finishing reading it at C:\inetpub\wwwroot\Project\temp\. I Close() and Dispose() the StreamReader properly already? I also gave full permission for NETWORK SERVICE account? Can anyone help me?

reader = new StreamReader(path + fileName);
DataTable dt = new DataTable();
            String line = null;
            int i = 0;

            while ((line = reader.ReadLine()) != null)
            {
                String[] data = line.Split(',');
                if (data.Length > 0)
                {
                    if (i == 0)
                    {
                        dt.Columns.Add(new DataColumn());
                        foreach (object item in data)
                        {
                            DataColumn c = new DataColumn(Convert.ToString(item));
                            if (Convert.ToString(item).Contains("DATE"))
                            {
                                c.DataType = typeof(DateTime);
                            }
                            else { c.DataType = typeof(String); }
                            dt.Columns.Add(c);
                        }
                        dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime)));
                        i++;
                    }
                    else
                    {
                        DataRow row = dt.NewRow();
                        row[0] = "";
                        for (int j = 0; j < data.Length; j++)
                        {
                            if (dt.Columns[j + 1].DataType == typeof(DateTime))
                            {
                                row[j + 1] = Convert.ToDateTime(data[j]);
                            }
                            else
                            {
                                row[j + 1] = data[j];
                            }
                        }
                        row[data.Length + 1] = DateTime.Now.ToString();
                        dt.Rows.Add(row);
                    }
                }
            }
            DataAccess dataAccess = new DataAccess(Constant.CONNECTION_STRING_NAME);
            dataAccess.WriteBulkData(dt, Constant.TABLE);
            reader.Close();
            reader.Dispose();
            File.Delete(path);

Solution

  • Your File.Delete method call should take path + fileName as parameter. This is because according to this link http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx path is the full path including the filename and your path variable includes only the folder name.