代码之家  ›  专栏  ›  技术社区  ›  RoseTeq

流转换为0字节[重复]

  •  2
  • RoseTeq  · 技术社区  · 1 年前

    在我安装了最新版本的Visual Studio 2022和之后。NET 8.0我在将流转换为文件时遇到了一个问题,要么保存本地文件,要么上传到FTP。

    到目前为止,我一直在使用以下代码,这非常棒。

    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");
    

    所以我将流转换为byte[],结果发现它有20357个字节。

    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.
    

    所以我试着先把它转换成FileStream,然后上传文件。但是仍然是0字节。

    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.
    

    附件是文件C:\test.png Properties的屏幕截图。

    enter image description here 文件:C:\test.png大小:0字节

    1 回复  |  直到 1 年前
        1
  •  2
  •   Guru Stron    1 年前

    您需要调整流的位置 之后 你已经写信给它了。试着移动 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");