欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET生成Google网站地图的代码

程序员文章站 2024-03-08 22:32:40
复制代码 代码如下:/// /// 生成google网站地图 /// ///
复制代码 代码如下:

/// <summary>
/// 生成google网站地图
/// </summary>
/// <returns></returns>
public static boolbuildgooglesitemap()
{
try
{
string rootdirectory = appdomain.currentdomain.basedirectory;
xmltextwriter writer = new xmltextwriter(httpcontext.current.server.mappath("~/googlesitemaps.xml"), encoding.getencoding("utf-8"));
writer.formatting = formatting.indented;
writer.writestartdocument();
writer.writestartelement("urlset", "http://www.google.com/schemas/sitemap/0.84");
//遍历扫描网站所有文件
showfiles(rootdirectory, writer);
writer.writeendelement();
writer.writeenddocument();
writer.close();
return true;
}
catch (exception err)
{
return false;
}
}
//遍历扫描网站所有文件
static void showfiles(string dirpath, xmltextwriter writer)
{
bool isread = true;
string[] notread ={ "app_data", "bin", "fckeditor", "js", "myadmin", "powerchatroom" };//排除这些文件夹
foreach (string s in notread)
{
string dirname = dirpath.substring(dirpath.lastindexof(@"\") + 1);
if (dirname == s)
{
isread = false;
break;
}
}
if (!isread)
return;
try
{
directoryinfo dir = new directoryinfo(dirpath);
foreach (fileinfo f in dir.getfiles())
{
string path = dir.fullname.replace(appdomain.currentdomain.basedirectory, "");//文件相对目录
//httpcontext.current.response.write(appdomain.currentdomain.basedirectory + "**********" + dir.fullname + "<br>");
writer.writestartelement("url");
writer.writestartelement("loc");
stringbuilder sb = new stringbuilder("/" + path + "/" + f.name);
sb.replace("//", "/").replace(@"\", "/");
writer.writestring(configurationmanager.appsettings["websiteurl"].tostring() + sb.tostring());
writer.writeendelement();
writer.writestartelement("lastmod");
writer.writestring(string.format("{0:yyyy-mm-dd}", f.lastwritetime));
writer.writeendelement();
writer.writestartelement("changefreq");
writer.writestring("always");//更新频率:always:经常,hourly:小时,daily:天,weekly:周,monthly:月,yearly:年
writer.writeendelement();
writer.writestartelement("priority");
writer.writestring("0.8");//相对于其他页面的优先权,此值定于0.0 - 1.0之间
writer.writeendelement();
writer.writeendelement();
}
foreach (directoryinfo d in dir.getdirectories())
{
showfiles(d.fullname, writer);
}
}
catch (exception) { }
}