Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream.SetLength() not truncating file #1454

Open
degosoft opened this issue Jul 23, 2024 · 3 comments
Open

stream.SetLength() not truncating file #1454

degosoft opened this issue Jul 23, 2024 · 3 comments

Comments

@degosoft
Copy link

I'm trying to truncate a file on a SFTP server by opening a stream and then setting the length. The docs state that the stream will be truncated to the provided length. But the file remains unchanged.

If the specified value is less than the current length of the stream, the stream is truncated and - if the current position is greater than the new length - the current position is moved to the last byte of the stream.

var _client = new SftpClient("host", "user", "pass");
try
{
    _client.Connect();
    using (var stream = _client.OpenWrite("\\file2.txt"))
    {
        stream.SetLength(9);
        //stream.Flush(); //no change with or without
    }
}
catch (Exception ex)
{
    Log(ex.Message);
}

The stream is working when I append more data to the file or if I make changes, but it won't get smaller. Thus I can't remove text from the file.

How can I remove all bytes from a file past a certain length?

@lymem
Copy link

lymem commented Jul 24, 2024

You are not doing what you think you are doing.
In order to change the length of a file, you need to read the file, truncate it, then write out the smaller file.
What you are doing is, opening a file to read/write on the sftp server into a stream, changing the length of the stream (not the file), and disposing of the stream.
This is working as intended. ie: not a bug.

@degosoft
Copy link
Author

Isn't the whole point of a stream that it's directly connected to the file? If I read the stream, it's from the file and if I write to the stream, it is reflected in the file. Changing the length should also reflect the file.

But there is no truncate option which only leaves delete and recreate and that changes a lot more then just the contents of a file. If you cannot truncate a file we have the same issue as #275

Or am I missing something and is there a way to truncate a file?

@Rob-Hague
Copy link
Collaborator

In fact, SetLength does at least look like it was written to change the length of the file as desired:

var attributes = _session.RequestFStat(_handle, nullOnError: false);
attributes.Size = value;
_session.RequestFSetStat(_handle, attributes);

But perhaps something is going wrong here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants