Question
· Apr 24, 2023

Using %Stream.FileBinary's ClassMethods to set where a Stream is saved

I have a %GlobalBinaryStream object that I'm trying to save as a local file after being received through a SOAP Web Service.

To do this, I created a %Stream.FileBinary object and wanted to set where the stream copied to this object would be saved by using either the DefaultStreamDir() ClassMethod or the NewFileName() ClassMethod. However, the documentation isn't very helpful on how to use these ClassMethods.

Right now, I have the below code:

set localStream = ##class(%Stream.FileBinary).%New()
set st = localStream.CopyFromAndSave(file) /// file is the %GlobalBinaryStreamObject
$$$QuitOnError(st)
set localStream = localStream.NewFileName(ext=<extension>,directory="path\to\folder\")

Is this correct? If not, instead of the above is the below code how we use the NewFileName() method:

set localStream = ##class(%Stream.FileBinary).NewFileName(ext=<extension>,directory="path\to\folder\")
set localStream.Filename = fileName
set st = localStream.CopyFromAndSave(file) /// file is the %GlobalBinaryStreamObject 
$$$QuitOnError(st)

If both of these are not correct, could someone write a rough skeleton code of how to save a %GlobalBinaryStream object as a local file in a specific location?

Discussion (4)2
Log in or sign up to continue

Hi @Punit Shah 

Use the method LinkToFile below a example.

C:\temp before create the file:


Execute the code

Set file = ##Class(%Stream.FileBinary).%New()
Set statusCode = file.LinkToFile("c:\temp\test_file.txt")
If ($System.Status.IsError(statusCode))
{
  Do $System.Status.DisplayError(statusCode)
  Return
}
Do file.WriteLine($ListBuild("Some bin data"))
Write $System.Status.DisplayError(file.%Save())

After execution:

Thank you @Cristiano Silva !

I had tried LinkToFile earlier but was getting an invalid error for some reason. From reading your solution, I realized that the folder needs to be created beforehand and then it can create a file inside it. If the folder doesn't exist (I was trying to create a file along with the folder using the LinkToFile method), the method fails.