1

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

我该怎么做呢?

4

2 回答 2

1

听起来您想编写一个重构工具。这是极其困难的,并且涉及实现大量的 C Sharp 编译器。

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

这是我从博客文章中找到的示例

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());
    }
}
}
于 2013-06-14T02:57:16.660 回答
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));
于 2013-06-14T02:49:53.907 回答