August 27, 2012

Named pipes in .Net

Recently I did a job involving sending SMS messages from a web service. The message application app is SMS Studio, from CodeSegment. This application is used for some time by our client and in the past we've only used VB Script to interface with it.
Using VB Script, the easy way to send an SMS was to make SMS Studio create a named pipe to receive incoming messages and 'place' the SMS content in that pipe by our script.

My problem

Seems straight forward. In vb script we create an fso object and write to the pipe. Should be as easy -if not easier- in .Net right? Wrong! The Filestream object in System.IO does not allow your to write to a 'device'. Anything named "\\.\[device]\[name]" is not allowed. Apparently "pipe" is considered a device... "\\.\pipe\SendSMS" dit not work..

Problem Solved?!

Making a long story short: What I was looking for was here: System.IO.Pipes. It is available as of  framework 3.5.

This is how we did it in vb script:
 Set fso = Server.CreateObject("Scripting.FileSystemObject")  
 Set pipe = fso.CreateTextFile("\\.\pipe\SendSMS")  

And the .Net way:
    Using pipe As New NamedPipeClientStream(".", "SendSMS", PipeDirection.Out, PipeOptions.Asynchronous)  
      Using sw As New StreamWriter(pipe)  
        sw.AutoFlush = True  
      End Using  
    End Using  
 Catch ex As Exception  
    Messagebox.Show(ex.Message & Environment.Newline & "SMS Studio offline?", "SMS not send")  
 End Try  

Notice that the pipe name in .Net is only the name "SendSMS", not the 'full' name ("\\.\pipe\SendSMS") like in vb script! Also we use NamedPipeClientStream, because we 'connect' to an existing pipe. It turns out to be this simple.

No comments:

Post a Comment