유용한 정보

[C#] 파일 오픈 및 읽기/쓰기

DevReff 2025. 4. 15. 05:58
728x90
728x90
SMALL
반응형

 

1. 파일 읽기

예제1) 텍스트 파일 읽기
/// <summary>
/// 파일의 내용을 문자열로 읽기
/// </summary>
/// <param name="path">파일경로</param>
/// <returns>파일내용(문자열)</returns>

string ReadAllText(string path)
{
try
{
if (File.Exists(path))
{
string rs = "";
using (StreamReader sr = new StreamReader(path))
{
rs = sr.ReadToEnd();
Trace.WriteLine(path);
}

return rs;
}
else
{
Trace.WriteLine($"[{path}] 파일이 없습니다.");
Trace.WriteLine(path);
}

Debug.Flush();
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
}

return string.Empty;
}

 

예제2) 스트림 데이터 읽기

/// <summary>
/// 스트림 데이터 읽기
/// </summary>
/// <param name="source">스트림</param>
/// <returns>바이트 데이터</returns>
byte[] ReadAllBytes(this Stream source)
{
long originalPosition = source.Position;
source.Position = 0;

try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = source.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = source.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}

byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
source.Position = originalPosition;
}
}

 

예제3) 문자단위로 읽기

/// <summary>
/// 파일의 내용을 문자 리스트로 읽기
/// </summary>
/// <param name="path">파일경로</param>
/// <returns>파일내용(List<char>)</returns>
List<char> Read(string path)
{
var rs = new List<char>();

try
{
if (File.Exists(path))
{
using (StreamReader sr = new StreamReader(path))
{
int c;
while (true)
{
c = sr.Read();
if (c == -1)
break;

rs.Add((char)c);
}

Trace.WriteLine(path);
}
}
else
{
Trace.WriteLine($"[{path}] 파일이 없습니다.");
Trace.WriteLine(path);
}

Debug.Flush();
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
}

return rs;
}

 

예제4) 텍스트 파일 쓰기
void Write(string filename, string sdata)
{
try
{
string msg = string.Format("[{0}] {1} {2} {3} : {4}"
, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
, sourceFilePath
, sourceLineNumber
, memberName
, sdata);

#if (DEBUG || TRACE)
if (File.Exists(filename))
using (StreamWriter file = new StreamWriter(filename, true))
{
file.WriteLine(msg);
Trace.WriteLine(msg);
}
else
using (StreamWriter file = new StreamWriter(filename))
{
file.WriteLine(msg);
Trace.WriteLine(msg);
}

Debug.Flush();
#endif
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}

 

예제5) 형식 지정하여 쓰기

void WriteFormat( string filename,  string fmt, params object[] args)
{
StackTrace st = new StackTrace();

try
{
string value = fmt;
StackFrame sf = new StackFrame(1, true);
string msg = "";

if (args != null && args.Length > 0)
value = string.Format(fmt, args);

if (sf.GetFileLineNumber() < 1)
msg = string.Format("[{0}] {1}.{2} : {3}"
, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
, sf.GetMethod().ReflectedType.Name
, sf.GetMethod().Name
, value);
else
msg = string.Format("[{0}] {1} {2} {3} : {4}"
, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
, sf.GetFileName()
, sf.GetFileLineNumber()
, sf.GetMethod().Name
, value);

#if (DEBUG || TRACE)
if (File.Exists(path))
using (StreamWriter file = new StreamWriter( filename , true))
{
file.WriteLine(msg);
Trace.WriteLine(msg);
}
else
using (StreamWriter file = new StreamWriter( filename ))
{
file.WriteLine(msg);
Trace.WriteLine(msg);
}


Debug.Flush();
#endif
}
catch (Exception ex)
{
Trace.WriteLine(GetAllFootprints(ex));
}
}

728x90
728x90
LIST