Public String SaveFile (byte [] bindata, string filepath, string filename, int type, string filetype)
{
/// Define and instantiate a memory stream to store the submitted byte array.
Memorystream M = new memorystream (bindata );
Filestream = NULL;
Try
{
String savepath = system. configuration. configurationsettings. deleetpath ["dcfilepath"];
// Not an absolute path
If (savepath. indexof (": \") <0) savepath = server. mappath (savepath );
// No backslash
If (! Savepath. endswith ("\") savepath + = "\\";
// Directory
Savepath + = filepath;
// Create a folder without folders
If (! Directory. exists (savepath ))
{
Directory. createdirectory (savepath );
}
If (type = 0)
{
Filename = "\" + datetime. now. day. tostring () + datetime. now. hour. tostring () + datetime. now. minute. tostring () + datetime. now. second. tostring () + datetime. now. millisecond. tostring ();
}
If (! File. exists (savepath + filename + filetype ))
{
Filename = "\" + datetime. now. day. tostring () + datetime. now. hour. tostring () + datetime. now. minute. tostring () + datetime. now. second. tostring () + datetime. now. millisecond. tostring ();
}
Filename = filename + filetype;
// Write an object
Filestream = new filestream (savepath + filename, filemode. Create );
M. writeto (filestream );
Streamwriter Sw = new streamwriter (savepath + ". txt ");
Sw. writeline (bindata. length. tostring ());
Sw. Close ();
Return "filepath. Replace (" \ ","/") + filename. Replace ("\\","/");
}
Catch
{
Return "An error occurred while uploading the file | 1 ";
}
Finally
{
M. Close ();
Filestream. Close ();
}
}
Sometimes the following function reports an error and does not know why. You can use the built-in Conversion Function of the upload control.
# Region converts a file into a binary stream convertfilestreamtobytebuffer
/// </Summary>
/// <Param name = "FILENAME"> </param>
/// <Returns> </returns>
Public byte [] getbinaryfile (string filename)
{
If (file. exists (filename ))
{
Filestream S = NULL;
Try
{
// Open an existing file for reading.
S = file. openread (filename );
Return this. convertstreamtobytebuffer (s );
}
Catch
{
Return new byte [0];
}
Finally
{
S. Close ();
}
}
Else
{
Return new byte [0];
}
}
# Endregion
# Region converts stream files into a binary byte array convert filestream into byte
/// </Summary>
/// <Param name = "thestream"> </param>
/// <Returns> </returns>
Public byte [] convertstreamtobytebuffer (system. Io. Stream thestream)
{
Int B1;
Memorystream tempstream = new system. Io. memorystream ();
Try
{
While (b1 = thestream. readbyte ())! =-1)
{
Tempstream. writebyte (byte) B1 ));
}
Return tempstream. toarray ();
}
Catch
{
Return new byte [0];
}
Finally
{
Tempstream. Close ();
}
}
# Endregion