C# 在aspx文件中重新生成类名

C# 在aspx文件中重新生成类名,c#,asp.net,webforms,web-application-project,C#,Asp.net,Webforms,Web Application Project,我正在尝试将网站(Web表单)转换为Web应用程序(也是Web表单)。我已经通过Visual Studio中的“转换为Web应用程序”转换了所有文件;这创建了一组designer.cs文件 据我所知,这些文件包含从main.cs文件中提取的代码,以避免开发人员对其进行修改;为了使其正常工作,.cs文件和.designer.cs文件中的类都声明为部分类 不幸的是,在开发.aspx页面时,代码隐藏类通常是随机命名的(通常只是“页面”),现在我发现了大量编译错误,这些错误发现所有这些不同页面之间的名称

我正在尝试将网站(Web表单)转换为Web应用程序(也是Web表单)。我已经通过Visual Studio中的“转换为Web应用程序”转换了所有文件;这创建了一组designer.cs文件

据我所知,这些文件包含从main.cs文件中提取的代码,以避免开发人员对其进行修改;为了使其正常工作,.cs文件和.designer.cs文件中的类都声明为部分类

不幸的是,在开发.aspx页面时,代码隐藏类通常是随机命名的(通常只是“页面”),现在我发现了大量编译错误,这些错误发现所有这些不同页面之间的名称冲突


有没有办法将这些类名重新生成为适当的名称,这样它们就不会相互冲突?即使只是基于文件路径的东西也足够了。

我编写了一个Python脚本来实现这一点。如果有人需要,这里是:

import fnmatch
import os
import re

def get_all_aspx_files(dir):
    aspx_files = []
    for root, dirnames, filenames in os.walk(dir):
        for filename in fnmatch.filter(filenames, '*.aspx'):
            aspx_files.append(os.path.join(root, filename))
    return aspx_files

def generate_class_name(file):
    class_name = file\
        .replace('./', '')\
        .replace('/', '_')\
        .replace('-', '_')\
        .replace('.aspx', '')
    return class_name

def inplace_regex_replace(filename, pattern, replace):
    with open(filename) as f:
        s = f.read()
    with open(filename, 'w') as f:
        s = re.sub(pattern, replace, s)
        f.write(s)

aspx_files = get_all_aspx_files('.')
for file in aspx_files:
    cs_file = file + '.cs'
    designer_cs_file = file + '.designer.cs'
    class_name = generate_class_name(file)
    inplace_regex_replace(file, 'Inherits="[A-Za-z0-9_]+"', 'Inherits="%s"' % class_name)
    inplace_regex_replace(cs_file, 'public partial class [A-Za-z0-9_]+', 'public partial class %s' % class_name)    
    try:
        inplace_regex_replace(designer_cs_file, 'public partial class [A-Za-z0-9_]+', 'public partial class %s' % class_name)
    except IOError as e:
        print e
您只需将其放在项目的根目录下,然后使用以下工具运行:

python script.py

在从网站转换到Web应用程序之前,也许您可以重命名代码隐藏文件。我同意,这是最好的做法。在转换项目之前准备项目。手动重命名它们可能不是一个选项。这需要几天的时间。你试过ReSharper吗?