user1305075
user1305075

Reputation: 23

Access to the path is denied C# error

I want my user to be able to hit the submit button and have a string write into a css file. When I hit the submit button, I am getting the error message:

Access to the path 'C:/.....' is denied

This happens when running the site from localhost and on my hosting (123reg)

protected void btnSubmit(object sender, EventArgs e) 
{ 
   using (StreamWriter writer = new StreamWriter("B00101168.css")) 
   { 
      writer.Write("Word "); 
      writer.WriteLine("word 2"); 
   } 
}

Upvotes: 0

Views: 4251

Answers (1)

Katie Kilian
Katie Kilian

Reputation: 6983

The first problem is, you can't write to a file without setting permissions on the folder. See this link for details. Essentially, you must give the Internet Guest Account permission to write to the folder.

But, the bigger problem is, you probably shouldn't be trying to dynamically write a CSS file anyway. At least, not the way you are trying to do it. Can you explain why you are trying to dynamically change a CSS file on your server? If you can explain what you are trying to accomplish, I might have some suggestions on how to do it that work better than what you are trying to do.

UPDATE: You're using WebForms, and you're trying to dynamically generate CSS. So here's one way to do that.

Use a generic page handler -- a file that ends in .ashx. You dynamically create the CSS however you're doing it now, but instead of writing it to a file, you output it directly to the browser. Here is some (untested!) code:

In the DynamicStyles.ashx file, there is basically nothing to add from what it automatically generates.

In the DynamicStyles.ashx.cs file:

public void ProcessRequest( HttpContext context )
{
    StringBuilder css = new StringBuilder();
    // Use the StringBuilder to generate the CSS 
    // however you are currently doing it.

    context.Response.ContentType = "text/css";
    context.Response.Write( css.ToString() );
}

Then, in your code that needs the CSS file, include it just like you would any other CSS:

<link rel="stylesheet" type="text/css" href="/path/to/DynamicStyles.ashx">

Upvotes: 1

Related Questions