gpt4 book ai didi

asp.net - 将单个文件 aspx 转换为代码隐藏

转载 作者:行者123 更新时间:2023-12-04 09:13:06 25 4
gpt4 key购买 nike

我正在 VS 2008 .Net 3.5 中处理一个网站(不是 Web 应用程序),它使用单个文件 .aspx 模型,其中服务器代码包含在 html 的头部部分,而不是使用 .aspx.cs代码隐藏页面。

我想快速转换文件以使用代码隐藏模型,但到目前为止我能做到的唯一方法是删除文件,创建一个新的同名代码隐藏 aspx 页面,然后手动复制在 .aspx 页面的 aspx 相关代码和 .aspx.cs 页面的服务器代码中。

有没有更快的方法来做到这一点?

我看过两篇文章似乎回答了这个问题,但不幸的是没有:
Working with Single-File Web Forms Pages in Visual Studio .NET
How do you convert an aspx or master page file to page and code behind?

两者都提供了一个简单的解决方案,其中 VS 可以完成腿部工作,您只需将其指向一个文件并进行拍摄。无论出于何种原因,它们都不起作用。第一篇文章似乎是指 VS 2002,第二篇文章似乎是指 Web 应用程序。

一个网站还有希望吗?

另外,也许我看错了,单页模型有优势吗?我确实计划很快将整个网站转换为 Web 应用程序,单页模型在 Web 应用程序中运行良好吗?

最佳答案

如果手动转换太耗时,并且自动转换不起作用,我认为您唯一的其他选择是构建自己的转换器。您可以编写一个简单的控制台应用程序,它在命令行上获取一个目录路径并处理该目录中的每个文件。这并不太难 - 在这里,我会让你开始:

using System;
using System.IO;

class Program
{
const string ScriptStartTag = "<script language=\"CS\" runat=\"server\">";
const string ScriptEndTag = "</script>";

static void Main(string[] args)
{
DirectoryInfo inPath = new DirectoryInfo(args[0]);
DirectoryInfo outPath = new DirectoryInfo(args[0] + "\\codebehind");
if (!outPath.Exists) inPath.CreateSubdirectory("codebehind");
foreach (FileInfo f in inPath.GetFiles())
{
if (f.FullName.EndsWith(".aspx"))
{
// READ SOURCE FILE
string fileContents;
using (TextReader tr = new StreamReader(f.FullName))
{
fileContents = tr.ReadToEnd();
}
int scriptStart = fileContents.IndexOf(ScriptStartTag);
int scriptEnd = fileContents.IndexOf(ScriptEndTag, scriptStart);
string className = f.FullName.Remove(f.FullName.Length-5).Replace("\\", "_").Replace(":", "_");
// GENERATE NEW SCRIPT FILE
string scriptContents = fileContents.Substring(
scriptStart + ScriptStartTag.Length,
scriptEnd-(scriptStart + ScriptStartTag.Length)-1);
scriptContents =
"using System;\n\n" +
"public partial class " + className + " : System.Web.UI.Page\n" +
"{\n" +
" " + scriptContents.Trim() +
"\n}";
using (TextWriter tw = new StreamWriter(outPath.FullName + "\\" + f.Name + ".cs"))
{
tw.Write(scriptContents);
tw.Flush();
}
// GENERATE NEW MARKUP FILE
fileContents = fileContents.Remove(
scriptStart,
scriptEnd - scriptStart + ScriptEndTag.Length);
int pageTagEnd = fileContents.IndexOf("%>");
fileContents = fileContents.Insert(PageTagEnd,
"AutoEventWireup=\"true\" CodeBehind=\"" + f.Name + ".cs\" Inherits=\"" + className + "\" ");
using (TextWriter tw = new StreamWriter(outPath.FullName + "\\" + f.Name))
{
tw.Write(fileContents);
tw.Flush();
}
}
}
}
}

30 分钟编码,30 分钟调试。有一些明显的错误——比如,如果你的代码在任何地方包含一个结束脚本标签 ,那么它将无法正确导出。结果不会很漂亮,但这应该可以处理 90% 的代码,并且您应该能够手动清理任何问题结果。在那里,这有帮助吗?

关于asp.net - 将单个文件 aspx 转换为代码隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/854545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com