나는 항상 정적 페이지를 동적으로 생성하는 것이 쉽지 않다고 생각했습니다. 나는 어제 온라인으로 그것을 보았고 나는 현기증이었다. 실제로는 매우 간단했습니다. 아이디어는 아마도 이와 같을 것입니다.
1 : HTML 페이지 템플릿을 만들고 특수 문자열을 사용 하여이 페이지에서 동적으로 표시하려는 장소를 나타냅니다 (예 : $ htmlstrstrstr $).
2 : 프로그램 에서이 HTML 페이지를 사용하여 str와 같은 문자열 변수를 읽으십시오.
3 : 문자열의 교체 방법을 사용하여 특수 문자를 첫 번째 단계에서 원하는 것으로 바꾸십시오.
4SAVE;
좋아, 너무 쉽다. 나는 오늘 C#에서 이와 같은 수업을 썼다. 나는 여전히 그것을 완전히 쓰고 있다고 생각했다. 방금 .NET과 연락을 취 했으므로 조언을 드리고 싶습니다.
참고 :이 범주의 코드는 모두 원본이 아니며 일부 코드는 네티즌 코드를 나타냅니다!
다음은 변환 클래스의 코드입니다
암호
1 사용 시스템;
2using system.text;
3 using system .web;
4using system. 구성;
5using system.io;
6namespace Solucky
7 {
8/** //// <요약>
9 /// aspxtohtml의 요약 설명.
10 /// 참고 :이 클래스를 사용하여 web.config 파일에서 템플릿 클래스를 구성 할 수 있습니다. 아래와 같이
11/** //*<AppSettings>
12 <add key = "templateFilePath"value = "htmlmoudel.htm" />
13 <add key = "htmlfilepath"value = "new/"> </add>
14 <키 = "errlogpath"value = "aspxtohtml_log.txt"> </add>
15 </appsettings>*/
16/** /// </summary>
17 공개 클래스 ASPXTOHTML
18 {
19/** /// <요약>
20 /// 템플릿 파일에서 교체 할 매개 변수 수
21 /// </summary>
22 개인 int _templateParamCount = 0;
23/** /// <요약>
24 /// 템플릿 파일이있는 경로
25 /// </summary>
26 개인 문자열 _TEMPLATEFILEPATH = CONFIGURATIONSETTINGS.AppSettings [ "TemplateFilePath"];
27/** /// <요약>
28 /// 변환 된 HTML 파일에 저장된 경로
29 /// </summary>
30 개인 문자열 _htmlFilePath = configurationSettings.AppSettings [ "htmlFilePath"];
31
32/** //// <요약>
33 /// 템플릿 페이지 인코딩
34 /// </summary>
35 개인 인코딩 _templatehtmlcode = encoding.getencoding ( "gb2312");
36
37/** /// <요약>
38 /// 변환 된 파일 인코딩
39 /// </summary>
40 개인 인코딩 _code = encoding.getencoding ( "gb2312");
41
42/** //// <요약>
43 /// 변환 된 HTML 파일 이름
44 /// </summary>
45 개인 문자열 _convertedFilename = "";
46/** //// <요약>
47 /// 템플릿 파일의 매개 변수
48 /// </summary>
49 개인 문자열 [] _templateFileParameter;
50
51/** /// <요약>
52 /// ASPX 파일의 매개 변수의 실제 값은 HTML 파일로 대체해야합니다.
53 /// </summary>
54 개인 문자열 [] _aspxFileParameter;
55
56 개인 문자열 _errlogpath = configurationSettings.AppSettings [ "errlogpath"];
57
58 속성#영역 속성
59
60/** //// <요약>
61 /// 템플릿 파일에서 교체 할 매개 변수 수
62 /// </summary>
63 공개 int templateparamcount
64 {
65 그려진
66 {
67이 this._templateparamcount;
68}
69 SET // 매개 변수 수를 할당 할 때 템플릿 파일의 매개 변수에 대해 실제 배열이 할당되어 ASPX 파일의 실제 값이 HTML 파일의 실제 값을 바꾸어 할당됩니다.
70 {
71 if (값 <0)
72 Throw New ArgumentException ();
73
74 if (값> 0)
75 {
76 this._templateparamcount = value;
77 // 템플릿 파일의 매개 변수
78 _TEMPLATEFILEPARAMETER = 새 문자열 [value];
79 // ASPX 파일의 매개 변수의 실제 값은 HTML 파일로 대체해야합니다.
80 _aspxFileParameter = 새 문자열 [value];
81}
82 else
83 this._templateparamcount = 0;
84}
85}
86
87/** //// <요약>
88 /// 템플릿 파일이있는 경로
89 ///
90 /// </summary>
91 공개 문자열 templateFilePath
92 {
93 get {return this._templatefilepath;}
94 세트 {this._templatefilepath = value;}
95}
96/** /// <요약>
97 /// 변환 된 HTML 파일에 저장된 경로
98 /// </summary>
99 공개 문자열 htmlfilepath
100 {
101 get {return this._htmlfilepath;}
102 세트 {this._htmlfilepath = value;}
103}
104
105/** /// <요약>
106 /// HTML 템플릿 파일 인코딩
107 /// </summary>
108 공개 인코딩 템플릿 htmlcode
109 {
110 get {return this._templatehtmlcode;}
111 세트 {this._templatehtmlcode = encoding.getEncoding (value.toString ());}
112}
113/** /// <요약>
114 /// 인코딩
115 /// </summary>
116 공개 인코딩 코드
117 {
118 get {return this._code;}
119 set {this._code = encoding.getEncoding (value.toString ());}
120}
121/** /// <요약>
122 /// 오류 파일의 경로가 있습니다.
123 /// </summary>
124 공개 문자열 errlogpath
125 {
126 get {
127 if (! (this._errlogpath == null)))
128 this._errlogpath;
129 else
130 "aspxtohtml_log.txt"리턴;
131}
132 세트 {this._errlogpath = value;}
133}
134
135
136 #endregion
137
138 작동#지역 작동
139
140/** /// <요약>
141 /// 변환 된 HTML 파일이있는 상대 파일 경로 가져옵니다.
142 /// 예 : htmlfilepath = "/news/"인 경우
143 /// 변환 된 HTML 파일 이름은 2005050505.html입니다
144 /// 그러면 반환 된 값은 /news/200505050505.html입니다
145 /// </summary>
146 /// <arevers> return null이 속성이 시작되면 startConvert 메소드가 호출되기 전에 </warting>
147 공개 문자열 htmlfilevirtualPath
148 {
149
150 {
151 if (! (this._convertedfilename == "")))
152 return this.htmlfilepath+this._convertedfilename;
153 else
154 리턴 널;
155}
156}
157
158/** /// <요약>
159 /// HTML 페이지 매개 변수 배열에 대한 지불 가치
160 /// </summary>
161 /// <param name = "param"> </param>
162 public void settemplateFileParameter (String [] param)
163 {
164 시도
165 {
166 if (param.length == this.templateparamcount)
167 this._templateFileParameter = param;
168 // else // 숫자는 원래 정의와 다릅니다
169 //
170}
171 Catch (System.Exception EX)
172 {
173 WriteErrfile (예);
174}
175}
176/** /// <요약>
177 /// HTML 파일로 대체 될 ASPX 파일의 매개 변수 배열 값을 지불합니다.
178 /// </summary>
179 /// <param name = "param"> </param>
180 Public void setapxFileParameter (String [] param)
181 {
182 시도
183 {
184 if (param.length == this.templateparamcount)
185 this._ASPXFILEPARAMETER = PARAM;
186 // else // 숫자는 원래 정의와 다릅니다
187 //
188}
189 Catch (System.Exception EX)
190 {
191 WriteErfile (예);
192}
193}
194/** /// <요약>
195 /// aspxtohtml 변환을 시작합니다
196 /// </summary>
197 /// <returns> 반환 값은 성공적인 생성 후 파일 이름입니다 </returns>
198 /// <warels>이 메소드를 호출하기 전에 SettemPlateFileParameter 및 SetAspXFileParameter 메소드가 해당 가치 지불 작업을 위해 요구되었는지 확인해야합니다 </warling>
199 Public String StartConvert ()
200 {
201 if (this._templatefileparameter.length == this._aspxfileparameter.length)
202 {
203 return writefile ();
204}
205 else {
206 리턴 널;
207}
208}
209/** /// <요약>
210 /// aspxtohtml 변환을 시작합니다
211 /// </summary>
212 /// <param name = "htmlparam"> html 템플릿의 모든 매개 변수 배열 </param>
213 /// <param name = "aspxparam"> ASPX 페이지는 HTML 템플릿 페이지의 매개 변수 값 배열을 대체해야합니다. </param>
214 /// <returns> 반환 값은 성공적인 생성 후 파일 이름입니다 </returns>
215 Public String StartConvert (String [] htmlparam, String [] aspxparam)
216 {
217 // 먼저 SettemPlateFileParameter 및 SetAspxFileParameter 방법을 호출하여 가치 지불 작업을 수행합니다.
218 SettemplateFileParameter (htmlparam);
219 SetaspxFileParameter (ASPXPARAM);
220 //
221 String fn = this.startConvert ();
222 //
223 _convertedFilename = fn;
224 //
225 반환 fn;
226}
227
228/** //// <요약>
229 /// 파일 이름을 생성하기 위해 임의 숫자를 추가하는 데 시간을 사용하십시오.
230 /// </summary>
231 /// <returns> </returns>
232 개인 문자열 getFileName ()
233 {
234 // 파일 이름을 생성하기 위해 임의의 숫자를 추가하는 데 시간을 사용합니다.
235 System.threading.thread.sleep (50);
236 string regttr = system.datetime.now.year.toString ();
237 String Monthstr = String.format ( "{0 : 0#}", System.DateTime.now.month);
238 string daystr = string.format ( "{0 : 0#}", System.DateTime.now.day);
239 string timestr = string.format ( "{0 : 0#}", System.DateTime.now.hour);
240 string minuteRStreth = string.format ( "{0 : 0#}", System.DateTime.now.minute);
241 string secondstr = string.format ( "{0 : 0#}", System.DateTime.now.second);
242 String millisecondstr = string.format ( "{0 : 000#}", System.dateTime.now.millisecond);
243 System.random rd = new System.random ();
244 return yearttr + monthstr + daystr + minutest + secondstr + millionsecondstr + string.format ( "{0 : 0000#}", rd.next (100)) + ". html";
245 // return dateTime.now.toString ( "yyyymmddhhmmss")+". html";
246}
247/** //// <요약>
248 /// 변환
249 /// </summary>
250 /// <returns> time </returns>에 의해 이름이 지정된 파일 이름을 반환합니다
251 개인 문자열 writefile ()
252 {
253
254 // 템플릿 파일을 읽습니다
255 String temp = httpcontext.current.server.mappath (this.templatefilepath);
256 streamreader sr = null;
257 String str = "";
258 시도
259 {
260 sr = new StreamReader (temp, this.templatehtmlcode);
261 str = sr.readtoend (); // 파일을 읽습니다
262}
263 캐치 (예외)
264 {
265 //httpcontext.current.response.write(exp.message);
266 //httpcontext.current.response.end ();
267 WriteErfile (예);
268}
마침내 269
270 {
271 sr.close ();
272}
273 // 컨텐츠 교체
274 // 현재 템플릿 파일은 str라는 변수로 읽었습니다.
275 for (int i = 0; i <this.templateparamcount; i ++)
276 {
277 str = str.replace (this._templatefileparameter [i], this._aspxfileparameter [i]);
278}
279
280 Return SaveFile (STR);
281}
282
283/** /// <요약>
284 ///
285 /// </summary>
286 /// <param name = "str"> </param>
287 /// <returns> </returns>
288
289 개인 문자열 저장 파일 (String Str)
290 {
291 // 파일 쓰기
292 스트림 라이터 sw = null;
293 시도
294 {
295
296 문자열 경로 = httpcontext.current.server.mappath (this.htmlfilepath);
297 // html 파일 이름
298 문자열 htmlfilename = getFilename ();
299 SW = 새 스트림 라이터 (Path + HtmlFilename, False, this.code);
300 Sw.Write (str);
301 Sw.flush ();
302 return htmlfilename;
303}
304 캐치 (예외)
305 {
306 WriteErrfile (예);
307}
마지막으로 308
309 {
310 Sw.close ();
311}
312 반환 "";
313}
314
315/** /// <요약>
316 /// URL을 통과하여 HTML 코드를 웹 페이지로 반환합니다.
317 /// </summary>
318 /// <param name = "url"> url </param>
319 /// <returns> </returns>
320 Public String geturltohtml (String URL)
321 {
322 시도
323 {
324 System.net.WebRequest WREQ = System.net.WebRequest.Create (URL);
325 System.net.webresponse wresp = wreq.getResponse ();
326 System.io.Stream respstream = wresp.getResponsestream ();
327 System.io.StreamReader reader = new System.io.streamReader (respstream, system.text.encoding.getEncoding ( "gb2312"));
328 return savefile (reader.readtoend ());
329
330}
331 캐치 (System.Exception EX)
332 {
333 WriteErrfile (예);
334}
335 반환 "";
336}
337 #endregion
338
339
340 구성 #영역 구조
341
342 공개 aspxtohtml ()
343 {
344 //
345 // todo : 여기에 생성자 로직을 추가하십시오
346 //
347}
348
349 개인 void settemplateparamcount (int templateparamcount)
350 {
351 if (TemplateParamCount> 0)
352 this.templateParamCount = TemplateParamCount;
353}
354/** //// <요약>
355 /// 교체 할 매개 변수 수를 제공
356 /// </summary>
357 /// <param name = "templateparamcount"> </param>
358 public aspxtohtml (int templateparamcount)
359 {
360 SettemPlateParamCount (TemplateParamCount);
361
362}
363/** //// <요약>
364 ///
365 /// </summary>
366 /// <param name = "templateparamcount"> html 템플릿 페이지의 매개 변수 수 </param>
367 /// <param name = "htmlfilepath"> 생성 된 html 파일의 폴더 경로 </param>
368 /// <param name = "TemplateFilePath"> HTML 템플릿 페이지 PATH </param>
369 public aspxtohtml (int templateparamcount, 문자열 htmlfilepath, 문자열 templateFilePath)
370 {
371 SettemPlateParamCount (TemplateParamCount);
372 this.htmlfilepath = htmlfilepath;
373 this.templateFilePath = TemplateFilePath;
374
375}
376 #endregion
377
378 #지역
379
380/** /// <요약>
381 /// 파일 메소드에 오류 쓰기 #region write errors on file method
382 /// </summary>
383 /// <param name = "ee"> </param>
384 Private void writeRerfile (예외 EE)
385 {
386
387 FILESTREAM FS1 = NEW FILESTREAM (httpcontext.current.server.mappath (errlogpath), system.io.filemode.append);
388 스트림 라이터 SW1 = 새로운 스트림 라이터 (FS1);
389 sw1.writeline("*********************************************************************************);
390 SW1.WRITELENILE ( "오류 날짜 :" + System.DateTime.now);
391 SW1.WRITELENE ( "오류 설명 :" + ee.message);
392 SW1.WRITELENE ( "오류 이름 :" + EE.Source);
393 SW1.WRITELENE ( "세부 사항 :" + ee.toString ());
394 SW1.WRITELENE ( "*************************************************************************************************************************************************************************************************************************************************************,
395 SW1.Close ();
396}
397 #endregion
398}
399}
400