如何使用C#代码更改C#项目的类名

时间:2013-06-14 02:31:59

标签: c#

例如,我有一个goodDay.cs类;我需要使用C#代码将其重命名为badDay.cs,并且必须确保项目仍然正常工作。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

可能是这样的:

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));

答案 1 :(得分:1)

听起来你想要编写一个重构工具。这非常困难,并涉及实现大量的C Sharp编译器。

幸运的是,微软最近开放了他们的编译器(并在.net中重写了它)。 Roslyn项目目前在CTP中,允许您弄清楚C#正在做什么,并将帮助您重构代码(像JetBrains这样的公司必须从头开始编写自己的C#解析器)。

这是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());
    }
}
}
相关问题