POST to a REST URL directly from ftp - c#

I would like to download a file from a FTP and directly POST to a REST URL without having to save in a temp folder, which I am currently doing. Works great, but not what I want to do. When I take a file directly from the FTP, the File.OpenRead takes not only the FTP path
ftp://xxxx.xxxxxx.xxx/
but it adds the project path
C://myProject/ProjectName
in front of it, thus causing a
The filename, directory name, or volume label syntax is incorrect.
Where am I going wrong?
using(var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/octet-stream");
using(var filestream = File.OpenRead(FTP_Path + FTP_filename))
using(var requestStream = client.OpenWrite(new Uri(fileUploadUrl), "POST"))
{
filestream.CopyTo(requestStream);
}
}

Related

ASP.NET Core 3.1 MVC download file not found until IIS app pool recycle or run website from localhost

I am making an ASP.NET Core 3.1 MVC with Entity Framework website on a Microsoft server running IIS 10 with basic user file upload and download functions. I can upload files to the _webHostEnvironment.WebRootPath from the web but when I try to download them it cannot find them. However, if I recycle the app pool I can download the file (I can also download it from the web after accessing the website on localhost on the server).
Here is the code for when I upload the file:
string uniqueFileName = null;
if (model.Data != null)
{
string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Data.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
model.Data.CopyTo(new FileStream(filePath, FileMode.Create));
}
Here is the code for when I download it:
public FileResult DownloadData(string fileName, string tempAddCode, string patientName)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(_webHostEnvironment.WebRootPath, "images") + "\\" + fileName);
var dataStream = new MemoryStream(fileBytes);
return new FileStreamResult(dataStream, new MediaTypeHeaderValue("application/pdf"))
{
FileDownloadName = patientName.ToLower().Replace(" ", "_") + ".pdf"
};
}
What is going on? Why would recycling the app pool fix this? Am I saving these user-uploaded files to the wrong location and ASP.NET is doing some sort of caching thing? I'd love any help finding a solution! Thanks.
With this line you open file stream and never close it.
model.Data.CopyTo(new FileStream(filePath, FileMode.Create));
Make sure you always dispose your streams, so files don't stay locked. Use code below to properly copy stream to file
using (var fs = new FileStream(filePath, FileMode.Create))
{
model.Data.CopyTo(fs);
}
What happens if you put a breakpoint in the DownloadData function, and step through? Does it successfully read the file into fileBytes, or do you get an exception - what exception do you get? Also check IIS logs to get the error code and post it, please.
Also, make sure the user that you're running under, has Write access to the folder. By Default, it will not.
To add, right-click on the folder, security, and add (from computer)
IIS AppPool\ [whatever the appPool name is].
IIS AppPool\MyAppPool

How can I get file from filepath in ASP.NET and return the file to the client

I am very new in ASP.NET. I want help about how to get file from specific location and send to the client through action controller.
To send any file to the client from the server I can use..............
var fileBytes = System.IO.File.ReadAllBytes(inkFormulation.DocumentPath);
var ext = ImageFormat.Jpeg;// the file extension you want to use
return base.File(fileBytes, $"image/{ext}", $"SampleImage.{ext}");
This is for image file. You can send any file with specific file extension.

Download text file from website using WebCLient

We recently switched our ftp site at work from ftp://address to https://ftp.address and now my application that retrieves files is unable to download files with expected content.
I previously used FtpWebRequest and it has been working for many years.
I am now trying to use WebClient and it downloads a file but it is not the text file I need. Instead, the contents of the file turns out to be some HTML.
Previous that worked:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(getAppSetting("URI") + getAppSetting("FilePath") + args[0].ToString());
request.Method = WebRequestMethods.Ftp.DownloadFile;
setCredentials(request);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Changed code to handle https:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
WebClient request = new WebClient();
setCredentials(request);
string file = request.DownloadString(getAppSetting("URI") + getAppSetting("FilePath") + args[0].ToString());
The result is a file that is downloaded but it contains HTML. I expect to have the contents of the file on the website I am pulling from.
After a couple of weeks of research, I finally found out what I needed to do and the answer was quite simple. I found out that our new website uses SSH so I installed SSH.Net via my nugent package to Visual Studio, and added "using Renci.SshNet;". I used the following code to download the file to my local drive:
using (SftpClient sftp = new SftpClient("ftp.website.com", 22,"username", "password")
{
sftp.Connect();
if (sftp.IsConnected)
{
using (Filestream fs = new FileStream("Output.txt", FileMode.Create))
{
sftp.DownloadFile("/file/Client/Input.txt", fs);
}
}
sftp.Disconnect();
}
This works perfectly. My file no longer downloads as an HTML file and I get my desired output. I hope this saves someone else a lot of time.

How to download files from OneDrive

I am looking to download my files in public folder from One Drive, but it doesn't download the files.
Here is the scenario:
In public folder I have another folder with multiple files in it and is accessible widely.
for test purpose I have shared all the files in public folder (I don't if it's proper way of sharing it).
The following links are provided for me to download the file:
From shared folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69!646&authkey=!AGRCGuw8Y2_p9mA&ithint=folder%2c.mp3
From public folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69%21646
Direct link http://1drv.ms/1z9XlW6 -
I am using BackgroundTransferRequest to download the file using below code:
string filePathToDownload = string.Empty, fileName = "111.mp3";
filePathToDownload = "http://1drv.ms/1z9XlW6";
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
The file is 300Kb, but this only downloads 6 Kb.
How can I directly download the file from the links above (any of them)?
thanks!
If you replace the word redir with download in the url you get the raw file instead of the webpage i.e.
https://onedrive.live.com/download?resid=DBBC281099F4FE69%21646
Basically, you can't. Those links are links to the web content that shows the files you have shared. If your scenario doesn't mind asking the user to log in to OneDrive, then you can use the Live SDK to access these files.
To access your public folder from Live SDK, you need to either use Live SDK to get the folder-id for your public folder, or convert the IDs in the URL you copied into the format the Live SDK uses:
folder.<user-id>.<folder-resid>
Where is the part of before the !. In general you shouldn't construct an ID, since it's possible the IDs will change in the future, and instead you should retrieve the ID from the service. However, with the URL you pasted the ID would be:
folder.DBBC281099F4FE69.DBBC281099F4FE69!646
Which will allow you to call
https://apis.live.net:443/v5.0/folder.DBBC281099F4FE69.DBBC281099F4FE69!646/files?access_token=<valid_token>
and retrieve the IDs for the individual files, which you can then download via Live SDK following these details: http://msdn.microsoft.com/en-US/library/dn659726.aspx#download_a_file
For those who are still looking for a response to that question.
The easiest way to find the file path is to go to One Drive on the web and right-click on the file that we want and select Embed. Ξ€hen on the right we see the info window to integrate our file into a page. Inside the iframe is the source of the file. Then we have to replace the word embed with the word download and that's it.
Try something like this
//we first need the file id
string id = string.Empty;
//we need to get all of the filenames stored in the root of the skydrive account
LiveOperationResult result = await this.client.GetAsync("me/skydrive/files");
//lets make a list of all these filenames
List<object> items = result.Result["data"] as List<object>;
//for every filename, check if it is what we want, in this case "sample.txt"
//if it is what we want, get the id and save it to out already defined id value
foreach (object item in items)
{
IDictionary<string, object> file = item as IDictionary<string, object>;
if (file["name"].ToString() == "sample.txt")
{
id = file["id"].ToString();
}
}
//to download the file we need to use the id + "/content"
LiveDownloadOperationResult result2 = await client.DownloadAsync(string.Format("{0}/content", id));
//once the file had downloaded, lets copy it to IsolatedStorage
Stream stream = result2.Stream;
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileToSave = storage.OpenFile("sample.txt", FileMode.Create, FileAccess.ReadWrite))
{
stream.CopyTo(fileToSave);
stream.Flush();
stream.Close();
}
}
here client is the object of LiveConnectClient class.
Import
using Microsoft.Live;
using Microsoft.Live.Controls;
Here is use txt file as an example. Go through this example:http://www.baileystein.com/2013/10/20/skydrive-how-to-upload-and-download-a-text-file-on-wp8/

ssis script task to create folders in Sharepoint document library

I am trying to create an SSIS package that gets a folder tree structure from a remote SQL DB and recreates that structure in a document library in Sharepoint.
I tried to (hard) code a Script Task to create just one folder but I'm getting this error:
http://img856.imageshack.us/img856/1386/helpel.png
After running only a part of this script:
Microsoft.Sharepoint.Client.dll
Microsoft.Sharepoint.Client.Runtime.dll
public void Main()
{
ClientContext clientContext = new ClientContext("http://spdemo.example.com/");
clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "SPDEMO");
Web rootWeb = clientContext.Web;
Dts.TaskResult = (int)ScriptResults.Success;
}
I've scoured the internet for solutions, but haven't found something that works for me.
So basically i need to find out how to:
create a folder
populate it with sub-folders
Copy files in bitestreams from SQL to Sharepoint, all in SSIS
Thanks in advance!
Regards,
Vlad Ardelean
After some research I found out that in order to reference a DLL in a SSIS Script Task it first has to be strong named
Instead, I have found an easier way to create folders and upload files:
public void CreateFolder(string url)
{
HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
request.Credentials = new NetworkCredential(user, pass);
request.Method = "MKCOL";
HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
}
public void UploadDocument(byte[] file, string destinationName)
{
byte[] buffer = file;
WebRequest request = WebRequest.Create(destinationName);
request.Credentials = new System.Net.NetworkCredential(user, pass);
request.Method = "PUT";
request.ContentLength = buffer.Length;
BinaryWriter writer = new BinaryWriter(request.GetRequestStream());
writer.Write(buffer, 0, buffer.Length);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}
url : represents the url path of the folder you want to create
http://spsite.host.com/DocLib/FolderToCreate
destinationName: path + document name
http://spsite.host.com/DocLib/FolderToCreate/DocToCreate.docx
Did you try running your code from a stand-alone windows application written in C# in Visual Studio?
If I get errors in SSIS, my preference is to test that code thoroughly in Visual Studio and then port it to a script task in SSIS.
If you haven't done folder creation and file copy to SharePoint, the below links might help.
Create a folder - http://thingsthatshouldbeeasy.blogspot.in/2009/09/how-to-add-folder-to-sharepoint-list.html
You can do the create folder step recursively untill you have created the destination tree structure.
Copy Files - http://msdn.microsoft.com/en-us/library/ms454491.aspx, http://msdn.microsoft.com/en-us/library/ms470176.aspx
I dont understand what you mean by copy file in bitestreams from SQL. If you want to read binary data from SQLServer via ADO.Net use System.Data.SqlDbType.VarBinary
Read the data from SQL server to a stream and write to a temp file, copy that temp file from local to SP. Or you may even write the data in a stream to SP directly without a temp file.

Categories

Resources