user1461511
user1461511

Reputation: 77

How to change the class name of a C# project using C# code

For Example, I have a goodDay.cs class; I need to rename it to badDay.cs using C# code and have to make sure the project is still working correctly.

How do i do this?

Upvotes: 1

Views: 4559

Answers (2)

Aron
Aron

Reputation: 15772

It sounds like you want to write a refactoring tool. This is extremely difficult, and involves implementing a large amount of the C Sharp compiler.

Luckily Microsoft has recently opened up their compiler (and rewritten it in .net). The Roslyn project is currently in CTP and will allow you use figure out what the C# is doing, and will help you with refactoring in code (companies like JetBrains had to write their own C# parser from scratch).

Here is a sample I found from a blog post

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Roslyn.Services;
using Roslyn.Scripting.CSharp;

namespace RoslynSample
{
class Program
{
    static void Main(string[] args)
    {
    RefactorSolution(@"C:\Src\MyApp.Full.sln", "ExternalClient", "ExternalCustomer");

    Console.ReadKey();
    }

    private static void RefactorSolution(string solutionPath, string fileNameFilter, string replacement)
    {
    var builder = new StringBuilder();
    var workspace = Workspace.LoadSolution(solutionPath);

    var solution = workspace.CurrentSolution;

    if (solution != null)
    {
        foreach (var project in solution.Projects)
        {
        var documentsToProcess = project.Documents.Where(d => d.DisplayName.Contains(fileNameFilter));

        foreach (var document in documentsToProcess)
        {
            var targetItemSpec = Path.Combine(
            Path.GetDirectoryName(document.Id.FileName),
            document.DisplayName.Replace(fileNameFilter, replacement));

            builder.AppendFormat(@"tf.exe rename ""{0}"" ""{1}""{2}", document.Id.FileName, targetItemSpec, Environment.NewLine);
        }
        }
    }

    File.WriteAllText("rename.cmd", builder.ToString());
    }
}
}

Upvotes: 1

sa_ddam213
sa_ddam213

Reputation: 43616

Maybe something like:

string solutionFolder = @"C:\Projects\WpfApplication10\WpfApplication10";
string CSName = "Goodday.cs";
string newCSName = "BadDay.cs";
string projectFile = "WpfApplication10.csproj";

File.Move(System.IO.Path.Combine(solutionFolder, CSName), System.IO.Path.Combine(solutionFolder, newCSName));
File.WriteAllText(System.IO.Path.Combine(solutionFolder, projectFile),File.ReadAllText(System.IO.Path.Combine(solutionFolder, projectFile)).Replace(CSName,newCSName));

Upvotes: 1

Related Questions