Skip to content

Instantly share code, notes, and snippets.

@remzmike
Last active April 17, 2017 15:32
Show Gist options
  • Save remzmike/9150cc54ece43ce3dbdaf5ae43539910 to your computer and use it in GitHub Desktop.
Save remzmike/9150cc54ece43ce3dbdaf5ae43539910 to your computer and use it in GitHub Desktop.
HttpPostedFile::SaveAs in .net 1, 2 and 4
// HttpPostedFile::SaveAs
// from .net 1.0
public void SaveAs(string filename)
{
FileStream fileStream = new FileStream(filename, 2);
try
{
if (this._stream.DataLength > 0)
{
fileStream.Write(this._stream.Data, this._stream.DataOffset, this._stream.DataLength);
}
fileStream.Flush();
}
finally
{
fileStream.Close();
}
}
// from .net 2.0 (same in 4.0)
public void SaveAs(string filename)
{
if (!Path.IsPathRooted(filename))
{
HttpRuntimeSection httpRuntime = RuntimeConfig.GetConfig().HttpRuntime;
if (httpRuntime.RequireRootedSaveAsPath)
{
throw new HttpException(SR.GetString("SaveAs_requires_rooted_path", new object[]
{
filename
}));
}
}
FileStream fileStream = new FileStream(filename, FileMode.Create);
try
{
this._stream.WriteTo(fileStream);
fileStream.Flush();
}
finally
{
fileStream.Close();
}
}
@remzmike
Copy link
Author

// relevant extraction

FileStream fileStream = new FileStream(filename, FileMode.Create);
try
{
	this._stream.WriteTo(fileStream);
	fileStream.Flush();
}
finally
{
	fileStream.Close();
}

@remzmike
Copy link
Author

// .net 1 does FileStream::Write
// .net 2+ does HttpInputStream::WriteTo (which does HttpRawUploadContent::WriteBytes)

// System.Web.HttpRawUploadedContent
internal void WriteBytes(int offset, int length, Stream stream)
{
	if (!this._completed)
	{
		throw new InvalidOperationException();
	}
	if (this._file != null)
	{
		int num = offset;
		int i = length;
		byte[] buffer = new byte[(i > this._fileThreshold) ? this._fileThreshold : i];
		while (i > 0)
		{
			int length2 = (i > this._fileThreshold) ? this._fileThreshold : i;
			int bytes = this._file.GetBytes(num, length2, buffer, 0);
			if (bytes == 0)
			{
				return;
			}
			stream.Write(buffer, 0, bytes);
			num += bytes;
			i -= bytes;
		}
		return;
	}
	stream.Write(this._data, offset, length);
}

@remzmike
Copy link
Author

remzmike commented Apr 17, 2017

// regular streams

// System.Web.HttpRawUploadedContent.TempFile
internal int GetBytes(int offset, int length, byte[] buffer, int bufferOffset)
{
	if (this._filestream == null)
	{
		throw new InvalidOperationException();
	}
	this._filestream.Seek((long)offset, SeekOrigin.Begin);
	return this._filestream.Read(buffer, bufferOffset, length);
}

@remzmike
Copy link
Author

// System.Web.HttpRequest
private HttpRawUploadedContent GetEntireRawContent()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment