Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I've been having a Server Error in '/' Application when im running my website. I have already tried troubleshooting the problem but i still can't figure out where the error is coming from. It states that the process cannot access the file because it is being used by another process. Before this happens, I created a code where if the admin wants to create a new brand, it will automatically write new piece of code on files that i target it to. And also if the admin wants to delete the brand, it will remove all the new code that i wrote previously.

Everything worked fine yesterday but visual studio is prompting me that there are changes made on files outside of IDE and it kept on checking for consistent lines on my code. I just clicked yes to all to update the code. But i want it to automatically reload the files so i went to Tools-Options-Documents-then i checked Reload modified files unless there are unsaved changes. After that, i can still run my website and create new brands but whenever i try to remove the brand, it is giving me this server error in '/' application.

Here is the full description of the error:

Server Error in '/' Application.

The process cannot access the file 'C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs' because it is being used by another process.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.IOException: The process cannot access the file 'C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs' because it is being used by another process.

Source Error:


Line 184: }
Line 185:
Line 186: System.IO.File.WriteAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs", result);
Line 187: }
Line 188: }

Source File: c:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx.cs Line: 186

Stack Trace:


[IOException: The process cannot access the file ' C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs' because it is being used by another process.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +216
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +1326
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +66
System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost) +73
System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost) +73
System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding, Boolean checkHost) +64
System.IO.File.WriteAllText(String path, String contents) +43
Pages_OverviewData.RemoveConnectionClassGuitarItems(String name) in c:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx.cs:186
Pages_OverviewData.GuitarBrandsGridViewBtn_Click(Object sender, EventArgs e) in c:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx.cs:73
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0

What I have tried:

C#
protected void GuitarBrandsGridViewBtn_Click(object sender, EventArgs e)
   {
       Button btn = sender as Button;
       GridViewRow gridrow = btn.NamingContainer as GridViewRow;
       int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[gridrow.RowIndex].Value.ToString());
       string name = GuitarBrandsGridView.Rows[gridrow.RowIndex].Cells[4].Text;
       con1.Open();
       cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
       cmd1.Connection = con1;
       int a = cmd1.ExecuteNonQuery();
       con1.Close();
       if (a > 0)
       {
           bindgridviewguitarbrands();
       }
       RemoveAddGuitarClass(name);
       RemoveOverviewGuitarDataCode(name);
       RemoveConnectionClassGuitarItems(name);
       RemoveOverviewGuitarDataASPX(name);
       System.IO.File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
       System.IO.File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
   }


C#
protected void RemoveAddGuitarClass(string name)
   {
       int counter = 0;
       string line;

       // Read the file and display it line by line.
       System.IO.StreamReader file1 = new System.IO.StreamReader(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs");

           while ((line = file1.ReadLine()) != null)
           {
               if (line.Contains("            case \"" + name + "\":"))
               {
                   break;
               }
               counter += 1;
           }
       file1.Close();
       RemoveAddGuitarClassCont(counter);
   }

   protected void RemoveAddGuitarClassCont(int counter)
   {
       int removeAt = counter;//or any thing you want
       removeAt -= 1;
       int linesToRemove = 20; //or any thing you want
       string s = System.IO.File.ReadAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs");
       List<string> arr = s.Split("\n".ToCharArray()).ToList();

       string result = "";
       for (int i = 0; i < linesToRemove; i++)
       {
           arr.RemoveAt(removeAt);
           result = "";
           foreach (string str in arr)
           {
               result += str + "\n";
           }

           System.IO.File.WriteAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs", result);
       }
   }

   protected void RemoveOverviewGuitarDataCode(string name)
   {
       int counter = 0;
       string line;

       // Read the file and display it line by line.
       System.IO.StreamReader file2 = new System.IO.StreamReader(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx.cs");

           while ((line = file2.ReadLine()) != null)
           {
               if (line.Contains("    //Start of Gridview Code for " + name + " Guitars"))
               {
                   break;
               }
               counter += 1;
           }
         file2.Close();
       RemoveOverviewGuitarDataCodeCont(counter);
   }

   protected void RemoveOverviewGuitarDataCodeCont(int counter)
   {
       int removeAt = counter;//or any thing you want
       removeAt -= 1;
       int linesToRemove = 41; //or any thing you want
       string s = System.IO.File.ReadAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx.cs");
       List<string> arr = s.Split("\n".ToCharArray()).ToList();

       string result = "";
       for (int i = 0; i < linesToRemove; i++)
       {
           arr.RemoveAt(removeAt);
           result = "";
           foreach (string str in arr)
           {
               result += str + "\n";
           }

           System.IO.File.WriteAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx.cs", result);
       }
   }

   protected void RemoveConnectionClassGuitarItems(string name)
   {
       int counter = 0;
       string line;

       // Read the file and display it line by line.
       System.IO.StreamReader file3 = new System.IO.StreamReader(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs");

           while ((line = file3.ReadLine()) != null)
           {
               if (line.Contains("    public static ArrayList GetItems" + name + "(string itemCategory)"))
               {
                   break;
               }
               counter += 1;
           }
       file3.Close();
       RemoveConnectionClassGuitarItemsCont(counter);
   }

   protected void RemoveConnectionClassGuitarItemsCont(int counter)
   {
       int removeAt = counter;//or any thing you want
       removeAt -= 2;
       int linesToRemove = 44; //or any thing you want
       string s = System.IO.File.ReadAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs");
       List<string> arr = s.Split("\n".ToCharArray()).ToList();

       string result = "";
       for (int i = 0; i < linesToRemove; i++)
       {
           arr.RemoveAt(removeAt);
           result = "";
           foreach (string str in arr)
           {
               result += str + "\n";
           }

           System.IO.File.WriteAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs", result);
       }
   }

   protected void RemoveOverviewGuitarDataASPX(string name)
   {
       int counter = 0;
       string line;

       // Read the file and display it line by line.
       System.IO.StreamReader file4 = new System.IO.StreamReader(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx");

           while ((line = file4.ReadLine()) != null)
           {
               if (line.Contains("    <h3>" + name + " Guitar Items Data</h3>"))
               {
                   break;
               }
               counter += 1;
           }
       file4.Close();
       RemoveOverviewGuitarDataASPXCont(counter);
   }

   protected void RemoveOverviewGuitarDataASPXCont(int counter)
   {
       int removeAt = counter;//or any thing you want
       removeAt -= 2;
       int linesToRemove = 44; //or any thing you want
       string s = System.IO.File.ReadAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs");
       List<string> arr = s.Split("\n".ToCharArray()).ToList();

       string result = "";
       for (int i = 0; i < linesToRemove; i++)
       {
           arr.RemoveAt(removeAt);
           result = "";
           foreach (string str in arr)
           {
               result += str + "\n";
           }

           System.IO.File.WriteAllText(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs", result);
       }
   }
Posted
Updated 21-Feb-17 2:46am
v2

It looks like you are trying to dynamically change the code of the web site and that's simply not going to work and is a very bad idea. Rather than trying to solve this issue re-architect how the site works such that you get the dynamic data and functionality you need without the need to re-write\compile the class files. What you're doing is simply not how websites are intended to work.
 
Share this answer
 
Comments
OriginalGriff 20-Feb-17 10:07am    
:thumbsup:
BebeSaiyan 20-Feb-17 10:19am    
well this solution is depressing and honestly i don't have any plan b yet..but hey thanks for advice, i appreciate you guys answering my question.
F-ES Sitecore 20-Feb-17 10:22am    
If you explain what you're ultimately trying to achieve by updating these files then someone may be able to point you toward a solution.
BebeSaiyan 21-Feb-17 7:20am    
hey guys if you a stack overflow account. I have posted a complete version on what i'm trying to do..feel free to check it out here : https://stackoverflow.com/questions/42367008/how-to-create-a-content-management-system-using-asp-net
F-ES Sitecore 21-Feb-17 8:52am    
See my other solution
If you're trying to do a CMS then this kind of code might get you on the right path. So here I have a page called ShowCategory.aspx that simply has this in the aspx page

<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    Category: <%=Request.QueryString["cat"] %>
</asp:Content>


Note I'm using the default WebApp template so it's a content page with a Master page. In the global.asax file I do this

void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext context = base.Context;

    string page = Path.GetFileNameWithoutExtension(context.Request.Url.LocalPath);

    if (page.Equals("ShowCategory", StringComparison.InvariantCultureIgnoreCase))
    {
        return;
    }
    context.RewritePath("~/ShowCategory.aspx?cat=" + page);
}


This is very basic, it take the page of the url and it keeps the url intact but the page is actually serves is ShowCategory.aspx and it passes the requested name on the querystring. So if I navigate to

/test.aspx

I'll see

ShowCategory: test

if I navigate to

/MyFolder/Cakes.aspx

I'll see

ShowCategory: Cakes

I'm only showing the parameter passed, in reality your code would then get a cakes from the database and show them, or whatever it is the page has to do.

So what you need to do is expand that concept with more sophisticated url analysis to work out what you actually want to show, or if you want to have the page handled as normal. eg you could decide on something like this

void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext context = base.Context;

    string[] seg = context.Request.Url.LocalPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

    if (seg.Length < 2)
    {
        return;
    }

    if (seg[0].Equals("Category", StringComparison.InvariantCultureIgnoreCase))
    {
        context.RewritePath("~/ShowCategory.aspx?cat=" + seg.Last());
    }
}


so now all page requests are handled as normal, unless it is "/category/something" and in that instance we show the ShowCategory page. Obviously you can extend that further so if it was "/search/something" you could show a Search.aspx page, or if it was "/category/ProductName" you should show a Product.aspx page that will show the details of that product.

Anyway, that's the basics of how you can start to build a CMS system.
 
Share this answer
 
v2
Comments
BebeSaiyan 21-Feb-17 10:42am    
thank you very much!
Look at the error message:
The process cannot access the file 'C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs' because it is being used by another process.

The file is in use. The chances are that somewhere else in your code is opening a stream on the file, but is failing to close it. As a result the file is locked and you cannot write to it and get the exception.
Check the rest of your code, and instead of manually closing the stream, use a using block each time to ensure that it is Closed and Disposed automatically for you:
C#
using (System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains("    public static ArrayList GetItems"+name+"(string itemCategory)"))
        {
            break;
        }
        counter += 1;
    }
}
Repeat that everywhere you create a stream, and your problem will likely go away.
 
Share this answer
 
Comments
BebeSaiyan 20-Feb-17 7:15am    
I have tried your solution but it is still not working.
OriginalGriff 20-Feb-17 7:26am    
Did you check everywhere you access the file?
Are there any other apps using the same file?
BebeSaiyan 20-Feb-17 8:19am    
I will post the whole code for better tracing. I have tried tons of revision in my code but still no luck.
BebeSaiyan 20-Feb-17 8:30am    
@OriginalGriff - I edit the question above with the complete code for my website. Please feel free to check it out.
OriginalGriff 20-Feb-17 10:07am    
Sitecore is right: What you are trying to do isn't going to work and should be completely rethought. Self modifying code is almost always a bad idea, and has to be viewed with extreme suspicion, particularly when seen in a multiuser environment.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900