Force XmlWriter or XmlTextWriter to use Encoding Other Than UTF-16

2 Comments »

You may have noticed the first line of XML output generated by XmlWriter or XmlTextWriter shows that the encoding defaults to UTF-16:

<?xml version="1.0" encoding="utf-16"?>

This happens even if you explicitly set the Encoding property in the XmlWriterSettings to something different, such as UTF-8:

StringBuilder sb  = new StringBuilder(); 
XmlWriterSettings settings = new XmlWriterSettings (); 
settings.Encoding = System.Text.Encoding.UTF8; 
XmlWriter writer = XmlWriter.Create (sb, settings); 

The problem occurs because the StringWriter defaults to UTF-16.  (It’s not clear from the example above, but the XmlWriter class uses a StringWriter to output the XML to the specified StringBuilder.) 

Read the rest of this entry »

Rename a File in C#

4 Comments »

If you want to rename a file in C#, you’d expect there to be a File.Rename method, but instead you must use the System.IO.File.Move method. 

You must also handle a special case when the new file name has the same letters but with difference case.  For example, if you want to rename “test.doc” to “Test.doc”, the File.Move method will throw an exception.  So you must rename it to a temp file, then rename it again with the desired case.

Here is the sample source code:

/// <summary> 
/// Renames the specified file. 
/// </summary> 
/// <param name="oldPath">Full path of file to rename.</param> 
/// <param name="newName">New file name.</param> 
static public void RenameFile( string oldPath, string newName ) 
{ 
    if (String.IsNullOrEmpty( oldPath )) 
        throw new ArgumentNullException( "oldPath" ); 
    if (String.IsNullOrEmpty( newName )) 
        throw new ArgumentNullException( "newName" );

    string oldName = Path.GetFileName( oldPath );

    // if the file name is changed 
    if (!String.Equals( oldName, newName, StringComparison.CurrentCulture )) 
    { 
        string folder = Path.GetDirectoryName( oldPath ); 
        string newPath = Path.Combine( folder, newName ); 
        bool changeCase = String.Equals( oldName, newName, StringComparison.CurrentCultureIgnoreCase );

        // if renamed file already exists and not just changing case 
        if (File.Exists( newPath ) && !changeCase) 
        { 
            throw new IOException( String.Format( "File already exists:n{0}", newPath ) ); 
        } 
        else if (changeCase)
        {
            // Move fails when changing case, so need to perform two moves
            string tempPath = Path.Combine( folder, Guid.NewGuid().ToString() );
            Directory.Move( oldPath, tempPath );
            Directory.Move( tempPath, newPath );
        }
        else
        {
            Directory.Move( oldPath, newPath );
        }
    } 
} 

Project is not selected for building in solution configuration

3 Comments »

When building a Visual Studio project, you may encounter the following error:

The project "MyProject" is not selected for building in solution configuration "Debug|Any CPU".

This error occurs because the project has not been configured to build in your Visual Studio solution.  The solution is simple:

Read the rest of this entry »

Visual Studio 2010 Service Pack 1 Beta

No Comments »

The beta version of Visual Studio 2010 Service Pack 1 (SP1) is now available for download.  SP1 Beta includes:

  • Many bug fixes
  • Performance improvements
  • Better platform support
  • Unit Testing on .NET 3.5
  • VB Compiler runtime switch
  • Other new features

Download VS2010 SP1 Beta
What’s New in VS2010 SP1 Beta

Application.ExecutablePath Can Return Wrong Path

1 Comment »

I discovered an interesting bug where the Application.ExecutablePath property returns the wrong path.  I haven’t debugged this thoroughly to determine why the problem occurs, but I thought I would share my experience.  Here’s my setup:

  • Visual Studio 2008
  • Solution with a DLL, and a WinForms EXE that references the DLL

When I run the application in the Visual Studio debugger, ExecutablePath returns the DLL path instead of the EXE path!  Note that if I run the EXE directly from Windows Explorer, ExecutablePath returns the EXE path correctly.

Read the rest of this entry »

Error CS0016: Could not write to output file

No Comments »

If you attempt to run an ASP.NET application hosted on IIS running on Windows Home Basic or Premium, you may receive the following error:

error CS0016: Could not write to output file ‘c:WindowsMicrosoft.NETFramework…

More information >

Step into: Stepping over method without symbols

2 Comments »

When debugging a project line-by-line in Visual Studio, you may receive this error:

Step into: Stepping over method without symbols ‘namespace’

This error occurs when you attempt to debug a DLL or EXE that is lacking a symbols (.pdb) file. 

Check the project’s binDebug folder to ensure the DLL/EXE in question has a corresponding pdb file.  If not, be sure to build the DLL/EXE with its project configuration set to “Debug” so that it will generate a pdb file. 

If the problem occurs with a third-party library, you may be out of luck because most third-party libraries do not include a pdb file, and therefore you cannot debug into them.

A StackOverflow article says this error may also occur if you attempt to debug a yield expression in a method that returns an IEnumerable, though I have not confirmed this.

Visual Studio Startup Project Not Saved in Solution File

No Comments »

If you have multiple Projects in a Visual Studio Solution, you can specify the “Startup Project,” which is the project that runs when you “Start Debugging” or “Start Without Debugging”.  The Startup Project appears bold in the Visual Studio Solution Explorer.  Step-by-step instructions to set the Startup Project can be found here.

If you use a source repository, perform automated builds, or do any Visual Studio solution file hacking, you may be disappointed to discover that the Startup Project is not saved in the Solution file (.sln), but rather in the Solution User Options file (.suo). 

The Solution User Options file contains settings — such as breakpoints, open files and views — that are specific to the current user.  Therefore the User Options file is not usually saved in a source repository, so it’s difficult to share the Startup Project across a team.

In addition, while the Solution File is an easy-to-modify XML file, the Solution User Options file is a hard-to-modify binary file, so it’s nearly impossible to programmatically set the Startup Project.

Which means that each developer must manually set the Startup Project for each Visual Studio Solution.

Run ASP.NET and IIS on Windows Vista and 7 Home Premium

2 Comments »

If you attempt to run an ASP.NET application hosted on IIS7.0 running on Windows Home Basic or Premium (Vista or Windows 7, x86 or x64), you may receive the following error:

error CS0016: Could not write to output file ‘c:WindowsMicrosoft.NETFramework64v2.0.50727Temporary ASP.NET Files…

Apparently this problem occurs because Windows Home Basic and Premium lack Windows Authentication.  So the common response on the Web is to upgrade to Windows Home Ultimate, Business or Professional.  However, there is no need to upgrade, as you can solve this problem with a few mouse clicks:

Read the rest of this entry »

Load a .NET Assembly into a Separate AppDomain So You Can Unload It

3 Comments »

There may be times when you wish to temporarily load a .NET assembly to inspect it, but you don’t want the assembly to remain in your program’s memory taking up resources.  Unfortunately, once your program loads an assembly, there is no way to unload it.  The best way is to create a separate AppDomain, load the assembly into that AppDomain, then unload the AppDomain when you are finished.

The following sample code loads a .NET assembly from disk, displays the name of every type defined in the assembly, then unloads the assembly:

AppDomain appDomain = null; 
try 
{ 
    string path = @"C:myAssembly.dll"; 
    byte[] buffer = File.ReadAllBytes( path ); 

    appDomain = AppDomain.CreateDomain( "Test" ); 
    Assembly assm = appDomain.Load( buffer ); 

    Type[] types = assm.GetTypes(); 
    foreach (Type type in types) 
    { 
        Console.WriteLine( type.FullName ); 
    } 
} 
catch (Exception ex) 
{ 
    Console.WriteLine( ex.Message ); 
} 
finally 
{ 
    if (appDomain != null) 
        AppDomain.Unload( appDomain ); 
}
« go backkeep looking »