파일 조작법
파일 시스템을 사용하기 위해서는 FileSystemObject 객체를 사용한다. 이 객체를 사용하려면 웹 상에서 동적으로 디렉토리의 생성과 삭제, 텍스트 파일의 생성과 삭제, 편집 등을 손쉽게 처리할 수 있다. 특히, 이런 파일의 조작은 클라이언트에서 작동할 수 있는 것이 아니라,
서버에서 작동할 수 있는 것이라는 점에 주의해야 한다.
FileSystemObject 객체를 사용하기 위해서는 Server 객체의 CreateOBject 메서드를 사용해서 FileSystemObject 객체의 인스턴스를 만든 다음 적절한 메서드를 사용해야 한다. 형식은 다음과 같다.
Set objFSO =CreateOBject("Scripting.FileSystemObject") -- 객체 인스턴스 생성 Set t objTest =objFSO.CreateTextFile("C:\test.txt") -- 메서드 사용
[1] 파일 정보 얻기(File 객체)
File 객체와 Files 콜렉션을 이용하면 지정한 파일의 객체를 얻어와서 그 파일의 여러 가지 정보
(파일 이름, 파일의 현재 디렉토리명, 이름 파일 크기, 수정 날짜 등) 를 가져올 수 있다.
config.sys 파일의 크기(size) 와 타입(type), 위치(path)를 정보를 얻어와서 출력한다.
CreateObject 메소드를 통해 FileSystemObject 객체의 인스턴스를 생성하고 그 객체의 GetFile
메소드를 통해 지정된 파일의 핸들을 가져온다.
create1.asp 파일 소스 코드
<!--#include virtual="./braverokmc/include/header.asp" --> <% Set fs =Server.CreateObject("Scripting.FileSystemObject") Set confile =fs.GETFile("C:\inetpub\wwwroot\asp-shoppingMall\ex\test.txt") %> </head> <body> <h2>파일 정보 얻기</h2> Config.sys 파일의 정보 <p> file size : <%= confile.size %> bytes <br /> file type : <%= confile.type %> bytes <br /> file path : <%= confile.path %> </body> </html>
출력 =>
파일 정보 얻기
Config.sys 파일의 정보
file size : 533 bytes
file type : 텍스트 문서 bytes
file path : C:\inetpub\wwwroot\asp-shoppingMall\ex\test.txt
[2] 파일 생성하기
CreateTextFile 이라는 메소드를 사용하여 텍스트 파일을 만들 수 있다. 이 메소드는 방문자 카운트 등을
만드는 경우 텍스트 파일에 그 내용을 저장하고자 할 때 자주 사용한다.
CreateTextFile 메소드 형식은 다음과 같다.
<% FSObject.CreateTextFile("파일이름", overwrite, unicode) %>
CreateTextFile은 세 개의 인자를 갖는다. 첫 번째 인자는 어느 경로에 어떤 이름의 텍스트 파일을 만들
것인지 그 전체 경로를 기입하는 곳이다.
두 번째 인자는 같은 이름의 파일이 이미 존재할 경우 그 파일을 덮어쓸 것인지, 그렇지 못하게 할 것인지를
지정하는 것이다. true 이면 덮어쓸 수가 있는 것이고, false 이면 덮어쓰기가
안된다.(overwrite = true | false)
세 번째 인자는 파일이 만들어질 때 유니 코드나 ASCll 파일로 생성할 것인가를 결정하는 것이다.
ture 이면 유니 코드로, false 이면 ASCll 코드로 생성된다. (unicode =default ASCll |-1)
<!--#include virtual="./braverokmc/include/header.asp" --> </head> <body> <h2>파일 생성하기</h2> <% Set fs =Server.CreateObject("Scripting.FileSystemObject") Set objFile=fs.CreateTextFile("C:\inetpub\wwwroot\braverokmc\test.txt", true, false) %> <% if fs.FileExists("C:\inetpub\wwwroot\braverokmc\test.txt") then Response.write "결과 : test.txt 파일이 만들어 졌습니다." else Response.write "결과 : test.txt 파일이 만들어지지 못했습니다. " end if %> </body> </html>
출력 =>
파일 생성하기
결과 : test.txt 파일이 만들어 졌습니다.
[3] 파일 읽기
텍스트 파일을 불러와서 화면에 출력하기 위해 CreateTextFile 메소드, OpenTextFile 메소드,
TextStream 메소드를 사용해야 한다. OpenTextFile 메소드를 사용하여 열린 파일의 내용을
TextStream 메서드를 사용하여 출력할 수 있다.
OpenTextFile 메소드 형식은 다음과 같다.
FSObject.OpenTextFile("파일이름", iomode, create, format)
인자 값의 내용의 다음과 같다.
iomode = 1 | 2 | 8 ( 1:read, 2:write, 3:append default 1)
create = true | false ( true 인 경우 파일이 없으면 생성한다.)
format = default ASCll | -1 (unicode)
test.txt 라는 파일을 열어서 OpenTextFile 메서드를 사용하여 브라우저로 출력하는 간단한 예이다.
소스 코드 중 OpenTextFile 부분에서 두 번째 인자가 "1" 로 세팅되어 있다.
이것은 파일을 읽는 경우이므로 읽기 전용인 1로 세팅하는 것이다. 만일 이 인자를 읽고 쓰기 모드인
8로 세팅하게 되면 에러가 발생할 것이다. 이유는 몇몇 속성과 메소들은 읽기 전용 모드에서만 동작하기
때문이다.
TextStream 의 속성 중에 하나인 AtEndOfStream 은 파일의 끝에 이르면 true를, 파일의 끝에 이르지
못했으면 false 를 리턴하게 되므로, DoWhile 문을 사용하여 파일의 끝을 만날 때까지 출력문을
수행한다.
ReadLine 메소드 다음에 나오는 <br /> 태그는 문장을 출력할 때 한 줄씩 나누어 출력하는 역할을 한다.
DoWhile 문장을 다음과 같이 코딩해도 같은 결과를 보여준다.
content =objFile.readall str =replace(content, char(13) & chr(10), "<br />") Response.write str
<%@Language="VBScript" CODEPAGE="65001" %> <% Response.CharSet="utf-8" Session.codepage="65001" Response.codepage="65001" Response.ContentType="text/html;charset=utf-8" %> <html lang="ko"> <head> <title>macaronics</title> <meta http-equiv="content-type" content="text/html"; charset="utf-8" > <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 위 3개의 메타 태그는 *반드시* head 태그의 처음에 와야합니다; 어떤 다른 콘텐츠들은 반드시 이 태그들 *다음에* 와야 합니다 --> <title>macaronics</title> <!-- 부트스트랩 --> <!-- 합쳐지고 최소화된 최신 CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <!-- 부가적인 테마 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> <!-- 합쳐지고 최소화된 최신 자바스크립트 --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <!-- IE8 에서 HTML5 요소와 미디어 쿼리를 위한 HTML5 shim 와 Respond.js --> <!-- WARNING: Respond.js 는 당신이 file:// 을 통해 페이지를 볼 때는 동작하지 않습니다. --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <% ' imode =1 |2 |8 (1:read, 2:write, 3:append default 1) ' create = true | false (true인 경우 파일이 없으면 생성한다.) ' format =default ascii | -1 (unicode) imode =1 create=false Set fs =Server.CreateObject("Scripting.FileSystemObject") Set objFile=fs.OpenTextFile("C:\inetpub\wwwroot\asp-shoppingMall\ex\test.txt", 1, -1) %> <h2>텍스트파일 읽기 예제</h2> text.txt 파일의 내용 <hr /> <% Do while objFile.AtEndOfStream <> true Response.write objFile.ReadLine & "<br />" loop %> </body> </html>
한글 깨짐이 나타날 경우 txt 파일을 euc-kr 로 변경 하면 된다.
출력 =>
텍스트파일 읽기 예제
text.txt 파일의 내용
이젠 울지 않을게 너를 믿으며 편히 있을게 나를 버린 사람도 용서할게 그리고 노력할게 너를 사랑하도록
*그동안 너를 피한건 나의 아픔들 때문에 너를 보면 늘 그를 생각했었고 사실 자신도 없었어
다른 사람을 만나 사랑 한다는게 두려웠던 거야 **너를 행복하게 해줄게 힘들어
하는 나를 더욱 안아준 너를 고마워 하며 내가 살아있는 날까지 영원히 있을게 너의 곁에 많이 괜찮아졌어
너 때문에 이제 널 알것같아 좋은 사람이란걸 반복 * ** ** 영원히 있을게 너의 곁에
Read more at: http://lyrics.jetmute.com/viewlyrics.php?id=71809
클라이언트로부터 입력받은 데이터를 서버에 파일로 저장하거나 로그로 남길 때 혹은 웹애플리케이션에 대한 옵션 값을
저장할 때는 대부분 텍스트 파일을 생성해서 저장한다. 이 경우, 보통 CreateTextFile 메서드와 OpenTextFile 메서드 등을
사용해서 처리하게 된다. 이런 메서드를 사용할 경우 TextStream 객체가 리턴되고, TextStream 객체의 메서드와 프로퍼티를
이용하여 파일을 제어할 수 있다.
TextStream 객체의 메서드
Close - 파일 닫기
Read(i) - 파일에서 i 개의 문자를 읽어온다.
ReadAll - 전체 문자열을 읽어 온다.
ReadLine - 파일에서 한 줄씩 읽는다.
Skip(i) - 파일을 읽을 때 i 개의 문자를 무시한다.
SkipLine - 파일을 읽을 때 다음 줄을 무시한다.
Write - 파일에 문자를 쓴다.
WriteLine - 문자를 쓰고 새 줄 문자를 쓴다.
WriteBlankLines(i) - 파일에 i 개의 엔터 값(라인 문자) 을 쓴다.
프로퍼티
AtEndOfLine - 파일 포인터가 파일 줄 끝에 있으면 True
AtEndOfStream - 파일 포인터가 파일 끝에 있으면 True
Column - 파일에서 현재 문자의 열 번호 리턴
Line - 파일에서 현재 줄 번호 리턴, 시작은 1
[4] 파일 쓰기
현재 존재하는 텍스트 파일을 OpenTextFile 메소드를 이용하여 연 다음 TextStream 객체의 메서드와 프로퍼티를 이용하여
파일에 데이터를 쓴다.
test.text 파일을 열어 데이터를 입력하고, OpenTextFile 메서드를 사용하여 파일을 연후, TextStream 메서드 중 WriteLine
메서드를 사용하여 파일에 내용을 추가하였다.
<%@Language="VBScript" CODEPAGE="65001" %> <% Response.CharSet="utf-8" Session.codepage="65001" Response.codepage="65001" Response.ContentType="text/html;charset=utf-8" %> <html lang="ko"> <head> <title>macaronics</title> <meta http-equiv="content-type" content="text/html"; charset="utf-8" > <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 위 3개의 메타 태그는 *반드시* head 태그의 처음에 와야합니다; 어떤 다른 콘텐츠들은 반드시 이 태그들 *다음에* 와야 합니다 --> <title>macaronics</title> <!-- 부트스트랩 --> <!-- 합쳐지고 최소화된 최신 CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <!-- 부가적인 테마 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> <!-- 합쳐지고 최소화된 최신 자바스크립트 --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <!-- IE8 에서 HTML5 요소와 미디어 쿼리를 위한 HTML5 shim 와 Respond.js --> <!-- WARNING: Respond.js 는 당신이 file:// 을 통해 페이지를 볼 때는 동작하지 않습니다. --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <% Set fs =Server.CreateObject("Scripting.FileSystemObject") Set objFile =fs.OpenTextFile("C:\inetpub\wwwroot\asp-shoppingMall\ex\test2.txt", 8, true) %> <h2>FSO 텍스트 파일에 쓰기를 완료하였습니다.</h2> <% objFile.WriteLine("이 텍스트 파일 작성 테스트이다.") objFile.WriteLine("이 텍스트 파일 OpenTextFile 메소드 사용하였다.") objFile.WriteLine("성공적으로 글쓰기가 완료되었습니다.") objFile.close %> </body> </html>
출력 test2.txt 파일 내용
이 텍스트 파일 작성 테스트이다. 이 텍스트 파일 OpenTextFile 메소드 사용하였다. 성공적으로 글쓰기가 완료되었습니다. 이 텍스트 파일 작성 테스트이다. 이 텍스트 파일 OpenTextFile 메소드 사용하였다. 성공적으로 글쓰기가 완료되었습니다.
[5] 디렉토리 정보 얻기 (Folder 객체)
Folder 객체를 생성하여 이 디렉토리에 대한 정보를 생성하고, 이 디렉토리에 대한 정보를 SubFolders 콜렉션을 이용하여 구한다.
<%@Language="VBScript" CODEPAGE="65001" %> <% Response.CharSet="utf-8" Session.codepage="65001" Response.codepage="65001" Response.ContentType="text/html;charset=utf-8" %> <html lang="ko"> <head> <title>macaronics</title> <meta http-equiv="content-type" content="text/html"; charset="utf-8" > <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 위 3개의 메타 태그는 *반드시* head 태그의 처음에 와야합니다; 어떤 다른 콘텐츠들은 반드시 이 태그들 *다음에* 와야 합니다 --> <title>macaronics</title> <!-- 부트스트랩 --> <!-- 합쳐지고 최소화된 최신 CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <!-- 부가적인 테마 --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> <!-- 합쳐지고 최소화된 최신 자바스크립트 --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <!-- IE8 에서 HTML5 요소와 미디어 쿼리를 위한 HTML5 shim 와 Respond.js --> <!-- WARNING: Respond.js 는 당신이 file:// 을 통해 페이지를 볼 때는 동작하지 않습니다. --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <h2>Folder 객체를 이용한 디렉토리 정보</h2> <% Dim strPathInfo, strPhysicalPath strPathInfo=Request.ServerVariables("PATH_INFO") strPhysicalPath=Server.MapPath(strPathInfo) Dim objFS, objFile Set objFS =CreateObject("Scripting.FileSystemObject") %> <% set objFile =objFS.GetFile(strPhysicalPath) set objFolder=objFile.ParentFolder Set fc=objFolder.SubFolders %> 현재 디렉토리 : <%= objFile.ParentFolder%> <br /> <ul> <% For Each fl in fc %> <li> 하위 디렉토리 : \<%=fl.name %> </li> <% Next %> </ul> </body> </html>
테스트 폴더를 sub , sub2 폴더를 생성한다.
출력 =>
Folder 객체를 이용한 디렉토리 정보
현재 디렉토리 : C:\inetpub\wwwroot\asp-shoppingMall\braverokmc\chapter7
- 하위 디렉토리 : \sub
- 하위 디렉토리 : \sub2
[6] 드라이브 정보 얻기(Drive 객체 )
Drive 객체를 사용하여 드라이브 리스트 정보(볼륨명, 사용 가능한 공간, 타입 등) 를 얻을 수 있다. 현재 FileSystemObject 객체에서는
드라이브에 대한 정보를 가져올 수는 있지만, 드라이브를 만들거나 삭제하는 기능은 지원하지 않는다.
- 예제
다음은 C 드라이브의 잔여 용량 정보를 출력하기 위해 GetDrive 메서드를 사용하였다.
C 드라이브의 핸들 값을 가지고 있는 Cdrive 를 freespace 라는 프로퍼티를 사용하여 남은 용량을 출력한다.
<!--#include virtual=./braverokmc/include/header.asp --> </head> <body> <% Set fs =Server.CreateObject("Scripting.FileSystemObject") Set Cdrive=fs.GetDrive("c:") %> <h2>드라이브 정보 얻기 1</h2> <hr /> <h3>C 드라이브의 남은 공간 : <%= Cdrive.freespace %> 바이트</h3> </body> </html>
출력 =>
드라이브 정보 얻기 1
C 드라이브의 남은 공간 : 226413387776 바이트
출처 :
ASP 쇼핑몰 제작 프로젝트따라하기
OWL 연구소 지음
소스 : https://github.com/braverokmc79/asp-shoppingMall
댓글 ( 4)
댓글 남기기