After I installed the latest version of Visual Studio 2022 and .NET 8.0 I ran into a problem converting stream to File, either saving local or uploading to FTP.
Till now I was using the following code, and it was great.
var bitmap = AlbumCover0.Source as BitmapSource;
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
var stream = new MemoryStream();
stream.Position = 0;
encoder.Save(stream);
SessionOptions sessionOptions = FTP.Login(); // using WinScp ftp client
using Session session = new();
session.Open(sessionOptions);
//The following line was working, but now its uploading 0 bytes.
session.PutFile(stream, "/htdocs/Music/Covers/" + ItemTxt2.Text + ".png");
So I converted the stream to byte[], and it turns out that it has for example 20357 bytes.
var bitmap = AlbumCover0.Source as BitmapSource;
...
encoder.Save(stream);
byte[] bytes = stream.ToArray(); // bytes[20357] for example
SessionOptions sessionOptions = FTP.Login();
...
session.PutFile(stream, "/htdocs/Music/Covers/" + ItemTxt2.Text + ".png"); //Still uploading 0 bytes.
So I tried to converting it first to a FileStream, and then upload the file. but still 0 bytes.
using (FileStream file = new FileStream("C:\\test.png", FileMode.Create))
{
stream.CopyTo(file); //0 bytes.
}
session.DoPutFiles("C:\\test.png", "/htdocs/Music/Covers/" + ItemTxt2.Text + ".png", false, new TransferOptions() { TransferMode = TransferMode.Binary }); // for sure its uploading 0 bytes.
Attached is a screenshot from the file C:\test.png Properties.
enter image description here File: C:\test.png Size: 0 bytes
You need to adjust the stream position after you have written to it. Try moving stream.Position = 0;
:
var stream = new MemoryStream();
encoder.Save(stream);
stream.Position = 0; // here
SessionOptions sessionOptions = FTP.Login(); // using WinScp ftp client
using Session session = new();
session.Open(sessionOptions);
//The following line was working, but now its uploading 0 bytes.
session.PutFile(stream, "/htdocs/Music/Covers/" + ItemTxt2.Text + ".png");