2012-11-07 1 views
1

는이 같은 직렬화 생성자를 통해 직렬화를 수행직렬화 생성자에서 예외가 발생하면 파일 이름을 얻는 방법?

private MyClass(SerializationInfo info, StreamingContext c) 
{ 
    try 
    { 
     MyIntVar = info.GetInt32("MyIntVar"); 
    } 
    catch(Exception) 
    { 
     Trace.WriteLine("Exception occured! Setting default value."); 
     MyIntVar = 4711; 
    } 
} 

내가 지금 달성하기 위해 노력하고있어 이름이 예외가 occures 때 직렬화를 beeing는되는 파일의 경로를 추적하는 것입니다. 그래서 두 가지 질문이 관련된 한

if(c is file) 
{ 
    Trace.WriteLine("Don't bother, I proceed anyway, but maybe you should repair the file " + FilePath); 
} 

: 같은

뭔가

  1. 나는 현재의 직렬화의 컨텍스트가 파일인지 어떻게 확인할 수 있습니까?
  2. 해당 파일 이름과 경로를 어떻게 얻을 수 있습니까? 당신이 자신StreamingContext을 만들었습니다, 그리고 .Context 속성을 통해 가능한 몇 가지 추가 정보를 한 경우 당신이 그렇게 할 수

답변

2

수있는 유일한 방법입니다.

var ctx = new StreamingContext(StreamingContextStates.File, "SomeFileName"); 
//               ^^^^ = context 
var serializer = new BinaryFormatter(null, ctx); 
// then use serializer.Serialize/.Deserialize 

다음 생성자 또는 콜백, 그것을 액세스 : 예를 들어 실제로

bool isFile = (c.State & StreamingContextStates.File) != 0; 

string filename = c.Context as string; 
if(filename != null) { 
    // ... 
} 

string은 매우 모호 - 나는 할 수있는 사용자 정의 컨텍스트 유형을 사용하여을 권합니다 ' 다른 어떤 것을 혼동하지 마십시오. 예 :

var ctx = new StreamingContext(StreamingContextStates.File, 
    new MyStreamingContext { File = "SomeFile" }); 
... 
class MyStreamingContext { 
    public string File {get;set;} 
} 
... 
var context = c.Context as MyStreamingContext; 
if(context != null) { 
    string file = context.File; 
    // ... 
} 
+0

WOW !!! 너의 빠른 anwer을위한 여분의 점. 이것은 내가 찾고 있던 것입니다. – MTR

관련 문제