System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'System.IO.StreamWriter'

StackOverflow https://stackoverflow.com/questions/19820269

  •  04-07-2022
  •  | 
  •  

Question

I tried to convert an Object variable into a StreamWriter. But, it does not work. What is the mistake ?

StreamWriter file = (StreamWriter) myObject;
Was it helpful?

Solution 3

Another moment of my stupidity. I had commented out the line that does this - Object myObject = Dts.Variables["yourStreamWriterHere"].Value; So, there was nothing inside myObject. Is there a null there ? In Java it is. Also, java gives you a nice nullPointerException. But, visual studio gives you a cryptic "Micro$lop™: Cannot find the cause of error. Contact Billy for more help. Keep your credit card handy just in case. Call center waiting times vary". Just irritating.

Anyway, the real error you get is -

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'System.IO.StreamWriter'.
   at ST_ffrrefr939322939392dfr.csproj.ScriptMain.Main()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

OTHER TIPS

The value of myObject is not (convertable to) a StreamWriter.

Try this:

if (myObject is StreamWriter) 
{
    var file = (StreamWriter) myObject as StreamWriter;
}

Before converting, check if it can be cast to a StreamWriter object by using the is keyword, as below:

if(myObject is StreamWriter)
{
//can be cast
}
else
{
//can not be cast
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top