C#에서는 문자 인코딩을 유지하면서 텍스트 파일을 여러 텍스트 파일 (분할 선 구분 기호는 빈 줄)로 분할하는 가장 효율적인 방법은 무엇입니까?텍스트 파일을 여러 파일로 분할하는 방법은 무엇입니까?
경우 : 사고를 피하고 싶은 사람들을위한 순수
Split("C:\\somefile.txt", "C:\\output-files-{0}.txt");
C#에서는 문자 인코딩을 유지하면서 텍스트 파일을 여러 텍스트 파일 (분할 선 구분 기호는 빈 줄)로 분할하는 가장 효율적인 방법은 무엇입니까?텍스트 파일을 여러 파일로 분할하는 방법은 무엇입니까?
경우 : 사고를 피하고 싶은 사람들을위한 순수
Split("C:\\somefile.txt", "C:\\output-files-{0}.txt");
나는에서는 StreamReader와 StreamWriter를 클래스를 사용합니다 CSV (쉼표로 구분 된 값) 파일이 있고 필드가 변경 될 때 파일을 분할하고, 변경 사항 (불필요한 따옴표 제외)으로 파일 이름 지정/주석 처리 및 주석/c 제거 (여기 # "로 시작하는 식별) ertain 라인
수정 방법 :
public void Split(string inputfile, string outputfilesformat)
{
System.IO.StreamWriter outfile = null;
string line;
string[] splitArray;
string nameFromFile = "";
try
{
using (var infile = new System.IO.StreamReader(inputfile))
{
while (!infile.EndOfStream)
{
line = infile.ReadLine();
splitArray = line.Split(new char[] { ',' });
if (!splitArray[0].StartsWith("\"#"))
{
if (splitArray[4].Replace("\"", "") != nameFromFile.Replace("\"", ""))
{
if (outfile != null)
{
outfile.Dispose();
outfile = null;
}
nameFromFile = splitArray[4].Replace("\"", "");
continue;
}
if (outfile == null)
{
outfile = new System.IO.StreamWriter(
string.Format(outputfilesformat, nameFromFile),
false,
infile.CurrentEncoding);
}
outfile.WriteLine(line);
}
}
}
}
finally
{
if (outfile != null)
outfile.Dispose();
}
}
로컬 경로 전화 :
string strpath = Server.MapPath("~/Data/SPLIT/DATA.TXT");
string newFile = Server.MapPath("~/Data/SPLIT");
if (System.IO.File.Exists(@strpath))
{
Split(strpath, newFile+"\\{0}.CSV");
}
+1하지만 빈 줄이 null이거나 빈 문자열이 아닌'System.Environment.NewLine' 값을 가질 수 있는지 궁금합니다. –
@adrift :'System.Environment.NewLine'을 모든 행의 마지막 (또는 시작 부분)에 추가하지 않겠습니까? – GPX
텍스트 파일의 "빈 줄"은 항상 \ r \ n (또는 OS 기반의 변형)입니다. 어떻게 찾을 수 있습니까? 텍스트 파일은 문자의 스트림입니다. –
: 당신은 다음과 같이이 방법을 부를 것이다
public void Split(string inputfile, string outputfilesformat) {
int i = 0;
System.IO.StreamWriter outfile = null;
string line;
try {
using(var infile = new System.IO.StreamReader(inputfile)) {
while(!infile.EndOfStream){
line = infile.ReadLine();
if(string.IsNullOrEmpty(line)) {
if(outfile != null) {
outfile.Dispose();
outfile = null;
}
continue;
}
if(outfile == null) {
outfile = new System.IO.StreamWriter(
string.Format(outputfilesformat, i++),
false,
infile.CurrentEncoding);
}
outfile.WriteLine(line);
}
}
} finally {
if(outfile != null)
outfile.Dispose();
}
}
:
당신의 제목과 실제 문제는 다르다. 텍스트 파일 (제목)을 분할하는 방법이나 더 효율적으로 (질문하는) 방법을 알고 싶습니까? –
나는 둘 다 찾고있다. 가장 효율적인 방법으로 텍스트 파일을 분할! – GPX