파일 처리 방법에 대한 몇 가지 질문이 있습니다. 내 프로그램에서 바이너리 직렬화와 비 직렬화를 사용한다. 그 위에 텍스트 파일을 내보내고 가져옵니다. 아래에 직렬화 코드 예제가 나와 있습니다. 오픈 파일 대화 상자를 사용하여 폴더/파일을 선택합니다.C#에서 파일을 처리하는 가장 좋은 방법은 무엇입니까?
이 내 바이너리 직렬화 방법 :
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentOutOfRangeException("fileName");
}
FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate);
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, Animals);
}
finally
{
fileStream.Close();
}
그리고이 내가 잡을 예외 :
try
{
administration.Load(fileName);
}
catch (NotSupportedException nonSupportedException)
{
MessageBox.Show(nonSupportedException.Message);
}
catch (UnauthorizedAccessException unauthorizedAccesException)
{
MessageBox.Show(unauthorizedAccesException.Message);
{
catch (SecurityException securityException)
{
MessageBox.Show(securityException.Message);
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
MessageBox.Show(directoryNotFoundException.Message);
}
catch (IOException IOException)
{
MessageBox.Show(IOException.Message);
}
내가 직렬화에 대해 동일한 예외를 잡을 수있어. 유일한 차이점은 다음과 같습니다.
if (File.Exists(fileName)) { }
FileStream fileStream = new FileStream(fileName, FileMode.Open);
Animals = formatter.Deserialize(fileStream) as List<Animal>;
데이터가 잘못되었을 때 어떻게해야합니까? 예 : 파일의 절반은 올바른 데이터를 가지고 나머지 절반은 그렇지 않습니다.
직렬화를위한 단위 테스트는 어떻게 작성해야합니까? SecurityException과 같은 많은 예외는 테스트하기 어렵습니다.
어떤 예외를 잡아야합니까? MSDN을 살펴 보았지만 목록에있는 모든 예외를 바로 잡아야하는지 잘 모르겠습니다. 나는 의도적으로 ArgumentOutOfRange 예외를 잡아 내지 못한다. 프로그래밍 실수를 포착하고 싶지 않기 때문이다.
텍스트 파일을 읽고 쓰는 데 동일한 질문이 있습니다. 테스트/예외 잡기에 차이가 있습니까? 유일한 차이점은 텍스트 파일을 쓰는 데 StreamWriter를 사용한다는 것입니다. 그리고 File.ReadAllLines을 사용하여 선택한 텍스트 파일을 읽습니다.
감사합니다.
정직하게 말하면 모든 질문은 귀하 또는 귀하의 최종 사용자/고객이 대답해야하는 요구 사항 인 것 같습니다. 직렬화에 대한 테스트 작성 : http://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializable –