.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Working with System.IO.Path static class

Posted By: hajan     Posted Date: August 30, 2010    Points: 0   Category :ASP.Net
Hello everyone. Today, I was exploring the System.IO namespace in .NET 4.0 on an ASP.NET web application where I came to few changes, comparing with the previous versions of .NET, related to the System.IO.Path static class. The Path class contains the same method names in .NET 2.0, 3.5 as well as 4.0, only (in .NET 4.0) new overloads are added to System.IO.Path.Combine() method. In the following blog post, I will show the usage of few methods belonging to the System.IO.Path static class, as well as, the changes in Combine() method added in .NET 4.0. Besides the first method that is available in the previous versions for combining two string paths, now in .NET 4.0 you can combine unlimited strings to the path. Note: For testing purpose, on your web application root, create folders with name Files, Files/SubFolder, Files/SubSubFolder and add three text files: text1.txt (in Files), text2.txt (in Files/SubFolder), text3.txt (in Files/SubFolder/SubSubFolder).   Here are few examples:             string path1 = System.IO.Path.Combine(Server.MapPath("Files"), "text1.txt"); //this will give the path to %WEBAPP_ROOT%/Files/text1.text -             string path2 = System.IO.Path.Combine(Server.MapPath("Files"), "SubFolder", "text2.txt"); //this will give

View Complete Post

More Related Resource Links

Static Class for Beginners

In general, the members of a class can be accessed by instance of that class when they are in public, but there comes a situation to access or call members of a class without an instance and this can be achieved by declaring them as static

abstract away the source of the connection string using a class with a static property.

ASP.NET provides a configuration system we can use to keep our applications flexible at runtime. In this article we will examine some tips and best practices for using the configuration system for the best results.

The element of a web.config file is a place to store connection strings, server names, file paths, and other miscellaneous settings needed by an application to perform work. The items inside appSettings are items that need to be configurable depending upon the environment, for instance, any database connection strings will change as you move your application from a testing and staging server into production.

Let's abstract away the source of the connection string using a class with a static property.

Localization not working in class library (composite control)



I have a class library called WEM.portal which used Resource files to localise text in my composite controls.

I store my resource files (eg MyResourceFile1.resx) in App_GlobalResources folder and then refer to them using

MyLabel1.text = My.Resources.MyResourceFile1.MyResourceKey1

This is all working ok until I create seperate files for each language such as MyResourceFile1.FR-fr.resx.

I have implemented this throughout my other web applications but the Class Library doesnt seem to want to work the same way

When I load the page it correctly showes the resourced keys which I have done through the web application BUT the resource keys in the composite controls does not seem to pick up the culture code.

Am I missing something stupid. Ive tried

  • changing the Build Action on the resource file to Content and Custom tool to GlobalResourceProxyGenerator
  • Creating a resourceManager but to no avail


System.Drawing.Image.Fromfile is not working


I am trying to get the height and width of the image dynamically.  The reason is I am loading multiple images using code, where the image name is from the database. 

Here is my code:

in the ascx page, I have an asp image

<asp:image id="imgInfo" runat="server" /> 


In the code behind

string ImagePath = "~/products/img/" + dataviewImgInfo[0]["imgName"].ToString();

System.Drawing Image imgProd = System.Drawing.Image.FromFile(ImagePath);

if(imgProd.Height > 200)

imgInfo.Height = 100;




imgInfo.Height = 200



WHen I run this page I am getting the folloiwng error

How do I find the file path from a namespace.class name?


I'm programatically looking ito a .aspx file and getting the file class name declared in its CodeBehind. For example, when analyzing myFile.aspx I read in its Page Directive and found its CodeBehind equals "myApplication\myPage.aspx.vb". Then I use the code below:


Dim Assm As System.Reflection.Assembly = System.Reflection.Assembly.LoadFrom("myApplication\bin\myApplication.dll")
Dim ClassType As Type = Assm.GetType("myApplication\myPage.aspx.vb")
' myBaseType = "myApplication.Forms.BasePage"
Dim myBaseType As System.Type = ClassType.BaseType


Now I want to read the BaseFile (class = myApplication.Forms.BasePage). However, to read in this file, I need I need to get its full path instead of its namespace.class hiearchy. In this case, the BasePage is wrapped in a different namespace declaration thus I cannot just change the '.' to '\' in order to get the path.

How can I get the path of BasePage so I can read it? Thank you - Frank

Cache vs Static Class

Hi All, I am sure this question has been posted many times, but have not got time to wade through. Apologies in advance! I am working on a new web application which has extremely high volumes of traffic, the application uses two large(ish) data tables (approx 15,000 rows/records each - both fairly 'wide' tables....) which are each the result of various JOINS and other intensive operations. The post query operations are unavoidable and the data structure has been optimised wherever possible. I am debating on using the Cache and CacheDependancy classes to store these tables, but fear the 'eviction' process due to the demand in traffic and server resources generally. I can certainly afford to build these tables once, on the first request (near Application Start), but should memory become scarce, do not want the cached data to be recreated during the application lifecycle and have concerns about how ASP.NET will manage demands on this data in such a crisis. For example, if during a period of time, available memory is at an all time low, I would anticipate that the CacheDependancy would keep recreating the tables for each request. (I don't know...) Note: The Cache API is not used elsewhere and the Application and Session scopes are hardly used. At present, I am using just a static class to store the two tables which works a

ASP.NET: Using a static class and methods for the WCF client

Traditionally in our web pages we have instantiated a service client in each page and then called the WCF methods from that instance, adding some caching code to check if the data exists and if not, make the WCF call and cache the data for the next time. As our site grows we find we're repeating this same pattern and are looking to move it all to a single class. Can we make that class static, with a single static instance of the WCF client, and static methods, safely? // pseudo-code // assume WcfDataService has a GetFoo(int i) method public static class WcfMethods { public static WcfDataService client = new WcfDataService("connectionType"); public static DataSet GetFoo(int i) { if (Cache["foo" + i] == null) { Cache.Insert("foo" + i, client.GetFoo(i)); } return Cache["foo" + i] as DataSet; } } Then in our pages we can just call WcfMethods.GetFoo(x) directly.  Figure we have 100 users visiting our various pages simultaneously.  Will this cause contention issues?  Like I mentioned, up till now we've not used static instances.  It's not caused any problems, but we're just looking to refactor.  I realize we could also use the above pseudo-code pattern using an instance class and methods instead static ones. I haven't dealt with threading or synchro

How to get a file path in a class library used by asp.net

 Hello,   I have an asp.net application which employs a class project to process xml files. I have an xsd file within the class project. To load the xsd file, I am not sure which path I should use. The following code snippet loads the xsd, and reads the xsd using the StreamReader. I am not sure how to set the value for xsdPath variable.// 2- Read Schema file content StreamReader SR = new StreamReader(xsdPath); // 3- Create a new instance of XmlSchema object XmlSchema Schema = new XmlSchema(); // 4- Set Schema object by calling XmlSchema.Read() method Schema = XmlSchema.Read(SR, new ValidationEventHandler(ReaderSettings_ValidationEventHandler)); Thanks  

Sharing of Non-Static member variables of a class using .NET Remoting

This kind of weird. I am trying to host an object of a class X (a class library class). This is a SAO and I have set the WellKnownMode as Singleton in the server configuration. <wellknown mode="Singleton" When multiple clients fetch the instance of the class X they can share the static member variables. Any changes made to the static variables are visible to each other. The problem is with the non-static member variables of the class. Each instance is having a local copy of the non-static variables. Why should that happen in case of a Singleton mode? Am I missing something for which this is happening? Any help will be appreciated.  A for apple, B for boy, C for c++

System.dbnull.value not working ..

For Each itm As GridViewRow In grid.Rows keyVal = grid.DataKeys(itm.RowIndex).Value If CType(itm.FindControl("chkSelect"), CheckBox).Checked Then Dim Advlnk As New AdvanceLink(keyVal) If CType(itm.FindControl("lblLastRMTest"), Label).Equals(System.DBNull.Value) Then ' If Advlnk.RMTest.Equals(System.DBNull.Value) Then Response.Write("this is null") I have tried different ways. ... How do I test my integer column for DBNull? I tried    If IsDBNull(Advlnk.RMTest) Then Response.Write( "this is null")     and this doesn't work either.

The system cannot find the path specified

I want to run an external command from my c# program and this is how I am running it, but getting the error: "The system cannot find the path specified".Please check my code and debugging details copied below and suggest what I need to fix. Thank You. string MappingCommand = MappingCommandPath + "Mapping.exe /FileName " + HL7FileServerIn + FName;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Process p = Process.Start(MappingCommand);On the debugger I get MappingCommand as: "\\\\csi-myserv-dkv\\DKV\\Projects\\CSIAccessioning\\Altova\\Mapping\\bin\\Debug\\Mapping.exe /FileName C:\\Orders\\ORM2.hl7"    On command prompt when I copy past the above MappingCommand and remove the escape sequences, the following command runs fine.\\csi-myserv-dkv\DKV\Projects\CSIAccessioning\Altova\Mapping\bin\Debug\Mapping.exe /FileName C:\Orders\ORM2.hl7Your help is highly appreciated.

To get the relative path in the class library

Hello, I have to access a relative path of the XSD file to validate a XML file. The XML file and the XSD file are part of the class library. How do I access the relative path in the class library? In case of website, I would use server.mappath(path). Is there anything similar to get the virtual path to the corresponding physical directory on the server in the class library? Thanks

CrystalReportsException: Load report failed - The system cannot find the path specified

I recently added a Crystal Report to a web application within Visual Studio 2010.  I'm using the Push method with a DataSet, and have a CrystalReportViewer control added to an aspx page.  When trying to test the report locally I'm getting an exception when performing the data binding on the CrystalReportViewer control...-----------------------------------------------------------------------------------------------------------------------------------Server Error in '/TestDevelopment' Application. The system cannot find the path specified. 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.Runtime.InteropServices.COMException: The system cannot find the path specified. Source Error: Line 7: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Line 8: BindReport() Line 9: CrystalReportViewer1.DataBind() Line 10: End Sub Line 11: Source File: C:\Documents and Settings\acwhifield\Desktop\VS_Projects\TestDevelopment\TestDevelopment\a\CR_Rpt_SubSelNotes.aspx.vb Line: 9 Stack Trace: [COMException (0x80004005): The system cannot find the path specified. ] CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocumentClass.Open(O

Task scheduler and System.IO.File.WriteAllText() not working properly

I have a simple console application that has this in mainline:  Console.WriteLine(System.String.Format("the current directory is: {0}", System.IO.Directory.GetCurrentDirectory())); System.IO. File.WriteAllText(@"test.txt", "new contents");   Console.ReadLine(); I compile this in VS 2010 and copy the EXE to a directory named "c:\test".  When I run this code in two different OS's via "Task Scheduler" and "Scheduled Task" I get different results.   In Windows Server 2003 R2 "Scheduled Task" this code will create a file as I would expect, c:\test\test.txt with the proper contents written to it.  When I run this same code on Windows 2008 R2 (64 bit version) "Task Scheduler" it writes the expected contents to an unexpected location, c:\C:\Windows\SysWOW64\test.txt. In both environments if I run the exe's from a command line, it writes to c:\test\test.txt as I would expect. As I understand it, if you don't fully qualify the file name in the first parameter of the WriteAllText method it will write the contents to the file in the directory of the executable however this seems to break down when running in the Windows 2008 Task Scheduler.  I know I can fully qualify the file name or put the expected path in a

Static Method System.Convert.ToDateTime() throws a FormatException on Windows7

Hello, There is a strange bug with the method System.Convert.ToDateTime(). Trying this simple statement Convert.ToDateTime("10/9/2010 17.39"); on a windows vista/xp works and the conversion is done. If you try that on a windows 7 than you get a format exception. Anybody has this problem? https://connect.microsoft.com/VisualStudio/feedback/details/597405/static-method-system-convert-todatetime-throws-a-formatexception-on-windows7#details Best regards. Thank you.

System.Diagnostics not working in IIS 6: Urgent

Hi All, I have developed a ASP.NET C# web page which connects to remote conmputer command prompt using PSEXEC.exe and executes some command where the output of the command will get copied to the page. It works fine in the VS 2005 IDE. If the page is accessed via IIS from IE, the task PSEXEC.EXE appears in task manager of the server with the system account privilege after the method is triggered but nothing happens. Please find my present settings in IIS and others: 1. APP Pool Identity to Local System (Predefined) and also to a configurable admin account. 2. <processModel userName="SYSTEM" password="AutoGenerate" /> in Machine.Config file Also I've tried impersonasation in web.config file to an admin account. I am not able to sort this problem, please help. I've tried a lot spending more time. Code Is:Process p = new Process(); string result = ""; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = @"C:\psexec.exe"; p.StartInfo.Arguments = @"\\nawrkxp613 -u domain\usename -p Password1 cmd.exe /c ipconfig"; p.Start(); StreamReader stdOut = p.StandardOutput; p.WaitForExit(); result = stdOut.R

how to jquery call a other call function other class is not static

how to jquery call a other call function other class is not static[WebMethod]    public static bool Verify(string username, string password)    {        //Do your logic with username, password  here        //I am just checking with admin/admin credentials            Console.WriteLine("Ritu");        string s="SELECT p.RETMSG FROM P_DOCSHARE(1001,1453,'1002,1012,1011','Add') P";                 CCUtility c;                c=new CCUtility();             c.JavascriptMessage(c.Insert_P(s));        return (username == "admin" && password == "admin");    }
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend