File upload in asp.net c# - c#

hey guys, m using an api of "Bits on the Run" following is the code of upload API
public string Upload(string uploadUrl, NameValueCollection args, string filePath)
{
_queryString = args; //no required args
WebClient client = createWebClient();
_queryString["api_format"] = APIFormat ?? "xml"; //xml if not specified - normally set in required args routine
queryStringToArgs();
string callUrl = _apiURL + uploadUrl + "?" + _args;
callUrl = uploadUrl + "?" + _args;
try {
byte[] response = client.UploadFile(callUrl, filePath);
return Encoding.UTF8.GetString(response);
} catch {
return "";
}
}
and below is my code to upload a file, m using FileUpload control to get the full path of a file(but m not succeeded in that)...
botr = new BotR.API.BotRAPI("key", "secret_code");
var response = doc.Descendants("link").FirstOrDefault();
string url = string.Format("{0}://{1}{2}", response.Element("protocol").Value, response.Element("address").Value, response.Element("path").Value);
//here i want fullpath of the file, how can i achieve that here
string filePath = fileUpload.PostedFile.FileName;//"C://Documents and Settings//rkrishna//My Documents//Visual Studio 2008//Projects//BitsOnTheRun//BitsOnTheRun//rough_test.mp4";
col = new NameValueCollection();
FileStream fs = new FileStream(filePath, FileMode.Open);
col["file_size"] = fs.Length.ToString();
col["file_md5"] = BitConverter.ToString(HashAlgorithm.Create("MD5").ComputeHash(fs)).Replace("-", "").ToLower();
col["key"] = response.Element("query").Element("key").Value;
col["token"] = response.Element("query").Element("token").Value;
fs.Dispose();
string uploadResponse = botr.Upload(url, col, filePath);
i read in some forums saying that for some security purpose you can't get fullpath of a file from client side. If it is true then how can i achieve file upload in my scenario ?

Yes, this is true, for security reason you cannot get the fullpath of the client machine, what you can do is, try the following,
Stream stream = fileUpload.PostedFile.InputStream;
stream.Read(bytes, 0, fileUpload.PostedFile.ContentLength);
instead of creating your own FileStream use the stream provided by the FileUploadControl. Hoep it shall help.

Related

Open filestream from sharepoint file

I want to open a filestream from a sharepoint file (Microsoft.SharePoint.Client.File) but I don't seem to find out how.
I only have access to Microsoft.SharePoint.Client because the Microsoft.SharePoint package can't be installed due to some errors.
This is the code I have so far:
ClientContext ctx = new ClientContext("https://factionxyz0.sharepoint.com/sites/faktion-devs");
ctx.Credentials = CredentialCache.DefaultCredentials;
Microsoft.SharePoint.Client.File temp = ctx.Web.GetFileByServerRelativeUrl(filePath);
FileStream fs = new FileStream(???);
You can only create a System.IO.FileStream if the file exists on a physical disk (or is mapped to a disk via the Operating System).
Workaround: Are you able to access the raw URL of the file? In which case, download the file to disk (if the size is appropriate) and then read from there.
For example:
var httpClient = new HttpClient();
// HTTP GET Request
var response = await httpClient.GetAsync(... SharePoint URL ...);
// Get the Content Stream
var stream = await response.Content.ReadAsSteamAsync();
// Create a temporary file
var tempFile = Path.GetTempFileName();
using (var fs = File.OpenWrite(tempFile))
{
await stream.CopyToAsync(fs);
}
// tempFile now contains your file locally, you can access it like
var fileStream = File.OpenRead(tempFile);
// Make sure you delete the temporary file after using it
File.Delete(tempFile);
FileStream must map to a file. The following code demonstrates how to get a stream via CSOM, then we can convert it to FileStream by using a temp file.
ResourcePath filepath = ResourcePath.FromDecodedUrl(filename);
Microsoft.SharePoint.Client.File temp = context.Web.GetFileByServerRelativePath(filepath);
ClientResult<System.IO.Stream> crstream = temp.OpenBinaryStream();
context.Load(temp);
context.ExecuteQuery();
var tempFile = Path.GetTempFileName();
FileStream fs = System.IO.File.OpenWrite(tempFile);
if (crstream.Value != null){
crstream.Value.CopyTo(fs);
}
As for Azure function temp storage, you may take a reference of following thread:
Azure Functions Temp storage
Or you can store data to Azure storage:
Upload data to blob storage with Azure Functions
Best Regards,
Baker Kong
Been a while since the question was asked, however, this is how I solved this while I was working on a project. Obviously passing in the credentials directly like this isn't the best way, but due to timing constraints I was not able to convert this project into a newer version of .NET and use Azure AD.
Note that the class is implementing an interface.
public void SetServer(string domainName) {
if (string.IsNullOrEmpty(domainName)) throw new Exception("Invalid domain name. Name cannot be null");
_server = domainName.Trim('/').Trim('\\');
}
private string MapPath(string urlPath) {
var url = string.Join("/", _server, urlPath);
return url.Trim('/');
}
public ISharePointDocument GetDocument(string path, string fileName) {
var serverPath = MapPath(path);
var filePath = string.Join("/", serverPath, TemplateLibrary, fileName).Trim('/');
var document = new SharePointDocument();
var data = GetClientStream(path, fileName);
using(var memoryStream = new MemoryStream()) {
if (data == null) return document;
data.CopyTo(memoryStream);
var byteArray = memoryStream.ToArray();
document = new SharePointDocument {
FullPath = filePath,
Bytes = byteArray
};
}
return document;
}
public Stream GetClientStream(string path, string fileName) {
var serverPath = MapPath(path);
var filePath = string.Join("/", serverPath, TemplateLibrary, fileName).Trim('/');
var context = GetClientContext(serverPath);
var web = context.Web;
context.Load(web);
context.ExecuteQuery();
var file = web.GetListItem(filePath).File;
var data = file.OpenBinaryStream();
context.Load(file);
context.ExecuteQuery();
return data.Value;
}
private static ClientContext GetClientContext(string serverPath) {
var context = new ClientContext(serverPath) {
Credentials = new SharePointOnlineCredentials("example#example.com", GetPassword())
};
return context;
}
private static SecureString GetPassword() {
const string password = "XYZ";
var securePassword = new SecureString();
foreach(var c in password.ToCharArray()) securePassword.AppendChar(c);
return securePassword;
}

Getting a file from "file://A/"

How can I get a file from external path same as "file://A/B/C/D/"
In local machine I have access to the path of "file://" but the user has not access.
Now I want to read some files from "file://A/B/C/D/" and make downloadable for user.
How can I do it?
(current directory is "https://localhost:44331/")
public async Task<IActionResult> DownloadDocument(string berichtsnummer)
{
var constantPath = "file://A/B/C/D/";
using (FileStream fileStream = System.IO.File.OpenRead(constantPath))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
return File(fileStream, "application/octet-stream");
}
}
when I click to download link, I get this error:
"IOException: The syntax for filename, directory name, or volume label
is incorrect:"
[
A view of path "file://A/B/C/D/":
A local file path is not "file://". You can read the file normally using the local file path as
var path = "C:\\...";
and then send to content to the client browser.
If the file is not on the local machine, the only way is to access it using a network share. You can then use UNC paths, like
var path = #"\\Server\Path\...";
That's important to change the constantPath to "\\\\A\\B\\C\\D\\"
private string[] GetListOfDocumentLink()
{
string path = string.Empty;
string constantPath = "\\\\A\\B\\C\\D\\";
string folderName = string.Empty;
string year = string.Empty;
// determine folderName and year.
path = constantPath
+ Path.DirectorySeparatorChar.ToString()
+ folderName
+ Path.DirectorySeparatorChar.ToString()
+ year;
var filter = Berichtsnummer + "*.pdf";
string[] allFiles = Directory.GetFiles(path, filter);
return allFiles;
}
Now you can send the path to DownloadDocument method:
public async Task<IActionResult> DownloadDocument(string path)
{
byte[] berichtData = null;
FileInfo fileInfo = new FileInfo(path);
long berichtFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
berichtData = br.ReadBytes((int)berichtFileLength);
return File(berichtData, MimeTypeHelper.GetMimeType("pdf"));
}

Asp .NET Read a file from a tar.gz archive

I have some files inside in one .tar.gz archive. These files are on a linux server.How can I read from a specific file inside this archive if I know it's name?
For reading direct from the txt file, I used the following code:
Uri urlFile = new Uri("ftp://" + ServerName + "/%2f" + FilePath + "/" + fileName);
WebClient req = new WebClient() { Credentials=new NetworkCredential("user","psw")};
string result = req.DownloadString(urlFile);
It's possible to read this file without copying the archive on the local machine, something like the code above?
I found a solution. Maybe this can help you guys.
// archivePath="ftp://myLinuxServer.com/%2f/move/files/archive/20170225.tar.gz";
public static string ExtractFileFromArchive(string archivePath, string fileName)
{
string stringFromFile="File not found";
WebClient wc = new WebClient() { Credentials = cred, Proxy= webProxy }; //Create webClient with all necessary settings
using (Stream source = new GZipInputStream(wc.OpenRead(archivePath))) //wc.OpenRead() create one stream with archive tar.gz from our server
{
using (TarInputStream tarStr =new TarInputStream(source)) //TarInputStream is a stream from ICSharpCode.SharpZipLib.Tar library(need install SharpZipLib in nutgets)
{
TarEntry te;
while ((te = tarStr.GetNextEntry())!=null) // Go through all files from archive
{
if (te.Name == fileName)
{
using (Stream fs = new MemoryStream()) //Create a empty stream that we will be fill with file contents.
{
tarStr.CopyEntryContents(fs);
fs.Position = 0; //Move stream position to 0, in order to read from beginning
stringFromFile = new StreamReader(fs).ReadToEnd(); //Convert stream to string
}
break;
}
}
}
}
return stringFromFile;
}

uploading a file using WCF in ASP.NET

I have created one WCF service that will upload the file. and after using that service I am trying to upload the file I am able to successfully upload the file but there is some issue with the FILESTREAM class.
The moment i clicked the button to upload the file when i checked by debugging the application i get to know that stream object is null.
I am passing the object of stream class to the WCF method.
But due to some issue that stream object is getting null.
due to that null object of stream class, image which is uploded getting empty in my folder
This is my code that I am using to upload the file
if (FileUpload1.HasFile)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileUpload1.PostedFile.FileName);
FileTransferServiceReference.ITransferService clientUpload = new FileTransferServiceReference.TransferServiceClient("BasicHttpBinding_ITransferService");
FileTransferServiceReference.RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();
string Path = System.IO.Path.GetDirectoryName(FileUpload1.FileName);
using (System.IO.FileStream stream = new System.IO.FileStream(FileUpload1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
uploadRequestInfo.FileName = FileUpload1.FileName;
uploadRequestInfo.Length = fileInfo.Length;
uploadRequestInfo.FileByteStream = stream;
clientUpload.UploadFile(uploadRequestInfo);
}
}
Code for WCF Service
public RemoteFileInfo DownloadFile(DownloadRequest request)
{
RemoteFileInfo result = new RemoteFileInfo();
try
{
// get some info about the input file
string filePath = System.IO.Path.Combine(#"c:\Uploadfiles", request.FileName);
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
// check if exists
if (!fileInfo.Exists) throw new System.IO.FileNotFoundException("File not found", request.FileName);
// open stream
System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// return result
result.FileName = request.FileName;
result.Length = fileInfo.Length;
result.FileByteStream = stream;
}
catch (Exception ex)
{
}
return result;
}
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"C:\upload\";
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
}
Spot the difference:
string uploadFolder = #"C:\upload\";
...
string filePath = System.IO.Path.Combine(#"c:\Uploadfiles", request.FileName);
As a general tip you might put your upload file path into an external configuration file, so that you can change it when you move your application onto a server where you need to store the data on a different drive or in a specific location.
Also that way you are always calling the same configuration entry so your upload path name is definitely going to be the same everywhere.

Check FileName From HttpHostedFileBase is File Name or File Path

I am developing an application which store filename in database. For Mozilla & Chrome it is showing FileName only but in IE it is showing full path of file. Now I want to check whether given filename is filename or filepath. Is there any way to do it?
Here is my code:
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
byte[] image = null;
var file = attachments.First();
// Some browsers send file names with full path. We only care about the file name.
string filePath = Server.MapPath(General.FaxFolder + "/" + file.FileName);
file.SaveAs(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (BinaryReader br = new BinaryReader(fs))
{
image = br.ReadBytes((int)fs.Length);
}
TempData["Image"] = image;
System.IO.File.Delete(filePath);
return Json(new { status = "OK", imageString = Convert.ToBase64String(image) }, "text/plain");
}
Well,If you go with getting filename only in any browser then you should write
Path.GetFileName(e.fileName);
It will return filename only in any browser
Thanks
Instead of check whether the file has a path or not, what you can do is to just use
GetFileName(path);method

Categories