How can i run .cmd file from http trigger azure function - c#

I want to run .cmd file using azure function. I want to run this in background process instead of main process of azure function.
I have already saved the cmd file on azure function platform using Kudu Editor. I can run this locally but after deploying its not working at all (I am also not getting any error).
string cmdFileLocation = #"D:\home\jobs.cmd";
Process proc = new Process();
ProcessStartInfo info = new ProcessStartInfo();
try
{
info.FileName = cmdFileLocation;
info.Arguments = name;
info.WindowStyle = ProcessWindowStyle.Minimized;
info.UseShellExecute = false;
proc.StartInfo = info;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
proc.Start();
proc.WaitForExit();
}
catch (Exception ex)
{
log.LogInformation("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
}
For testing there is curl command in cmd file. The curl will trigger on local machine using azure function as I can see the request coming (https://webhook.site) but after deplying nothing happens.

Here is an easy way of getting any .exe/.cmd running as a web service. You just specify the input parameters to your exe/cmd in a configuration file. You can use binary files as inputs to the exe by specifying a URL to download it from.
Here's what the configuration file looks like
{
"name": "consoleAppToFunctions",
"input": {
"command": "ffmpeg.exe -i {inputFile} {output1}",
"arguments": {
"inputFile": {
"url": "https://1drv.ms/v/<link-to-file>"
//binary file input
},
"output1": {
"localfile": "out.mp3"
//stored in a temp folder
}
}
},
"output": {
"folder": "outputFolder",
"binaryFile": {
"returnFile": "*.mp3",
"returnFileName": "yourFile.mp3"
}
}
}
Here is the AZURE FUNCTION CODE for the same:
#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;
//Code from https://github.com/Azure-Samples/functions-dotnet-migrating-console-apps/edit/master/code/run.csx
//Written by Ambrose http://github.com/efficientHacks and Murali http://github.com/muralivp
public class ExeArg
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string localPath = req.RequestUri.LocalPath;
string functionName = localPath.Substring(localPath.LastIndexOf('/')+1);
var json = File.ReadAllText(string.Format(#"D:\home\site\wwwroot\{0}\FunctionConfig.json",functionName));
var config = JsonConvert.DeserializeObject<dynamic>(json);
var functionArguments = config.input.arguments;
var localOutputFolder = Path.Combine(#"d:\home\data", config.output.folder.Value, Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
Directory.CreateDirectory(localOutputFolder);
var workingDirectory = Path.Combine(#"d:\home\site\wwwroot", functionName + "\\bin");
Directory.SetCurrentDirectory(workingDirectory);//fun fact - the default working directory is d:\windows\system32
var command = config.input.command.Value;
var argList = new List<ExeArg>();
//Parse the config file's arguments
//handle file system, local file etc. and construct the input params for the actual calling of the .exe
foreach (var arg in functionArguments)
{
var exeArg = new ExeArg();
exeArg.Name = arg.Name;
var value = (Newtonsoft.Json.Linq.JObject)arg.Value;
var property = (Newtonsoft.Json.Linq.JProperty)value.First;
exeArg.Type = property.Name;
exeArg.Value = property.Value.ToString();
var valueFromQueryString = await getValueFromQuery(req, exeArg.Name);
log.Info("valueFromQueryString name=" + exeArg.Name);
log.Info("valueFromQueryString val=" + valueFromQueryString);
if(!string.IsNullOrEmpty(valueFromQueryString))
{
exeArg.Value = valueFromQueryString;
log.Info(exeArg.Name + " " + valueFromQueryString);
}
if(exeArg.Type.ToLower() == "localfile" || exeArg.Type.ToLower() == "localfolder")
{
exeArg.Value = Path.Combine(localOutputFolder, exeArg.Value);
exeArg.Type = "string";
}
if(string.IsNullOrEmpty(exeArg.Value))
{
//throw exception here
}
argList.Add(exeArg);
}
//call the exe
Dictionary<string, string> paramList = ProcessParameters(argList, localOutputFolder);
foreach (string parameter in paramList.Keys)
{
command = command.Replace(parameter, paramList[parameter]);
}
string commandName = command.Split(' ')[0];
string arguments = command.Split(new char[] { ' ' }, 2)[1];
log.Info("the command is " + command);
log.Info("the working dir is " + workingDirectory);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = commandName;
p.StartInfo.Arguments = arguments;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
File.WriteAllText(localOutputFolder+"\\out.txt",output);
//handle return file
log.Info("handling return file localOutputFolder=" + localOutputFolder);
string outputFile = config.output.binaryFile.returnFile.Value;
string outputFileName = config.output.binaryFile.returnFileName.Value;
var path = Directory.GetFiles(localOutputFolder, outputFile)[0];
log.Info("returning this file " + path);
var result = new FileHttpResponseMessage(localOutputFolder);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = outputFileName
};
return result;
}
private static Dictionary<string, string> ProcessParameters(List<ExeArg> arguments, string outputFolder)
{
Dictionary<string, string> paramList = new Dictionary<string, string>();
foreach (var arg in arguments)
{
switch (arg.Type)
{
case "url":
string downloadedFileName = ProcessUrlType((string)arg.Value, outputFolder);
paramList.Add("{" + arg.Name + "}", downloadedFileName);
break;
case "string":
paramList.Add("{" + arg.Name + "}", arg.Value.ToString());
break;
default:
break;
}
}
return paramList;
}
//you can modify this method to handle different URLs if necessary
private static string ProcessUrlType(string url, string outputFolder)
{
Directory.CreateDirectory(outputFolder);
string downloadedFile = Path.Combine(outputFolder, Path.GetFileName(Path.GetTempFileName()));
//for oneDrive links
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.AllowAutoRedirect = false;
WebResponse webResp = webRequest.GetResponse();
webRequest = (HttpWebRequest)HttpWebRequest.Create(webResp.Headers["Location"].Replace("redir", "download"));
webResp = webRequest.GetResponse();
string fileUrl = webResp.Headers["Content-Location"];
WebClient webClient = new WebClient();
webClient.DownloadFile(fileUrl, downloadedFile);
return downloadedFile;
}
private async static Task<string> getValueFromQuery(HttpRequestMessage req, string name)
{
// parse query parameter
string value = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, name, true) == 0)
.Value;
//if not found in query string, look for it in the body (json)
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
value = value ?? data?[name];
return value;
}
//this is to delete the folder after the response
//thanks to: https://stackoverflow.com/a/30522890/2205372
public class FileHttpResponseMessage : HttpResponseMessage
{
private string filePath;
public FileHttpResponseMessage(string filePath)
{
this.filePath = filePath;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Content.Dispose();
Directory.Delete(filePath,true);
}
}
Here you can find more on this. Hope it helps.

Related

AWS S3 - move folder with all files problem

I am trying to move data for example;
Source = "Uploads/Photos/" to Destination="Uploads/mytest/"
I am getting error like that but but when i give a specific file this works.
Basically, I want to move folder with all files.
My code is below;
public async Task<MoveResponse> MoveObject(MoveRequest moveRequest)
{
MoveResponse moveResponse = new MoveResponse();
CopyObjectRequest copyObjectRequest = new CopyObjectRequest
{
SourceBucket = moveRequest.BucketName,
DestinationBucket = moveRequest.BucketName + "/" + moveRequest.Destination,
SourceKey = moveRequest.Source,
DestinationKey = moveRequest.Source,
};
var response1 = await client.CopyObjectAsync(copyObjectRequest).ConfigureAwait(false);
if (response1.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
moveResponse.IsError = true;
moveResponse.ErrorMessage = "Files could not moved to destination!";
return moveResponse;
}
return moveResponse;
}
I hope, you are using high level S3 API's.
Check out this sample code
private void uploadFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
string directoryPath = textBoxBasePath.Text + listBoxFolder.SelectedItem.ToString().Replace("[", "").Replace("]", "");
string bucketName = comboBoxBucketNames.Text;
string FolderName = listBoxFolder.SelectedItem.ToString().Replace("[", "").Replace("]", "");
try
{
TransferUtility directoryTransferUtility = new TransferUtility(new AmazonS3Client(AwsAccessKeyID, AwsSecretAccessKey, RegionEndpoint.USEast1));
TransferUtilityUploadDirectoryRequest request = new TransferUtilityUploadDirectoryRequest
{
BucketName = bucketName,
KeyPrefix = FolderName,
StorageClass = S3StorageClass.StandardInfrequentAccess,
ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256,
Directory = directoryPath,
SearchOption = SearchOption.AllDirectories,
SearchPattern = "*.*",
CannedACL = S3CannedACL.AuthenticatedRead
};
ListMultipartUploadsRequest req1 = new ListMultipartUploadsRequest
{
BucketName = bucketName
};
var t = Task.Factory.FromAsync(directoryTransferUtility.BeginUploadDirectory, directoryTransferUtility.EndUploadDirectory, request, null);
t.Wait();
MessageBox.Show(string.Format("The Directory '{0}' is successfully uploaded", FolderName));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{ }
}

Upload file in asp.net and angular 7 null

I upload image from angular to .net core but the file input I receive always null , with the postman , it's receive exactly. I don't know why ?
Can you help me how to solve it?
Thank you so much !
[HttpPost("upload-file")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
try
{
//var file = Request.Form.Files[0];
var rnd = FileHelper.RandomNumber();
//var file = file;
var folder = "Folder";
var index = file.FileName.LastIndexOf('.');
var onlyName = file.FileName.Substring(0, index);
var fileName = onlyName + rnd;
var extension = Path.GetExtension(file.FileName);
var folderThumb = folder + "Thumbnail";
var fileNameThumb = fileName + "Thumbnail";
var t1 = Task.Run(() => FileHelper.SaveFile(folder, fileName, file));
await Task.WhenAll(t1);
var path = new MediaResponseModel()
{
Url = Url.Action("GetFile", "Media", new { folder = folder, fileName = string.Format("{0}{1}", fileName, extension) }, Request.Scheme),
UrlThumbnail = Url.Action("GetFile", "Media", new { folder = folderThumb, fileName = string.Format("{0}{1}", fileNameThumb, extension) }, Request.Scheme),
Title = onlyName
};
return Ok(path);
}
catch (System.Exception e)
{
throw e;
}
}
handleFileInput(files: FileList) {
const file = files.item(0);
this.fileToUpload = {};
this.fileToUpload.data = files.item(0);
this.fileToUpload.fileName = files.item(0).name;
}
onUpload() {
const formData = new FormData();
formData.append('file', this.fileToUpload.data, this.fileToUpload.name);
this.http.post('http://localhost:56000/api/media/upload-file', formData).subscribe(res => console.log(res));
}

Directory is being locked by windows service after first File.Move

I have a windows service that monitors a directory for new files and, when a file is created/copied into that directory, it renames it and does some processing.
I'm using File.Move to rename the file.
It works fine when I use the exact same code from a console application, but now when it runs as a Windows Service.
Code that initialize the file watcher(s)
public void StartFileSystemWatcher()
{
listFileSystemWatcher = new List<FileSystemWatcher>();
foreach (var customFolder in listFolders)
{
var dir = new DirectoryInfo(customFolder.FolderPath);
if (customFolder.FolderEnabled && dir.Exists)
{
var fileSWatch = new FileSystemWatcher
{
Filter = customFolder.FolderFilter,
Path = customFolder.FolderPath,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
EnableRaisingEvents = true
};
fileSWatch.Created += (senderObj, fileSysArgs) => FileSWatch_Created(senderObj, fileSysArgs, customFolder.VSTSUrl);
listFileSystemWatcher.Add(fileSWatch);
logger.Info(string.Format("Starting to monitor files with extension ({0}) in the folder ({1})", fileSWatch.Filter, fileSWatch.Path));
}
else
{
logger.Info(string.Format("File system monitor cannot start because the folder ({0}) does not exist", customFolder.FolderPath));
}
}
}
private void FileSWatch_Created(object sender, FileSystemEventArgs e, string vstsUrl)
{
PostFileInfoToVSTS(e.FullPath, vstsUrl);
}
Code that's run when the file is created
private void PostFileInfoToVSTS(string filePath, string vstsUrl)
{
try
{
var fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
var fileParts = fileName.Split(new char[] { '.' });
if (fileParts.Length == 6)
{
//rename the file
var fileNewName = $"{fileParts[2]}.{fileParts[3]}.{fileParts[4]}.TXT";
var fileNewPath = $"{Path.GetDirectoryName(filePath)}\\oldfiles\\{fileNewName}";
File.Move(filePath, fileNewPath);
//prepare vsts request
var request = new VSTSRequest();
request.Variables.Region.Value = fileParts[0];
request.Variables.Sparc.Value = fileParts[1];
request.Variables.SystemName.Value = fileParts[2];
request.Variables.Type.Value = fileParts[3];
request.Variables.Name.Value = fileParts[4];
request.Variables.Filename.Value = fileNewName;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(vstsUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", ConfigurationManager.AppSettings["VSTSAuthentication"]);
//post to vsts
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(request));
streamWriter.Flush();
streamWriter.Close();
}
//read response
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
var json = JsonConvert.DeserializeObject<dynamic>(result);
logger.Info($"File '{fileNewPath}' processed. ReleaseId: {json.id}.");
}
}
else
{
logger.Info($"File '{fileName}' wasn't processed. Name is not in the correct format.");
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
The first time I copy a file into that directory, it works fine, but the following times, I get a System.IO.IOException: The process cannot access the file because it is being used by another process.

Send file from angular to create new and download from .net

I've been trying to download .xml file, but sadly unsuccesfully.
From angular side I am sending *.xml file. In .NET side I take it to process and create a new *.xml file. And I need to download that new file, however I can't really find out how to workaround it.
this is my file-component.ts:
OnSubmit(value, File) {
const params1: FormData = new FormData();
params1.append('File', this.fileToUpload, this.fileToUpload.name);
params1.append('ProcessingMode', value.processingMode);
params1.append('StartDate', value.startDate.formatted);
const params = {
'File': this.fileToUpload,
'ProcessingMode': value.processingMode,
'StartDate': value.startDate.formatted
};
this.mapsConfigurationService.postFile(value, this.fileToUpload, value.startDate.formatted)
.subscribe((res: any) => {
this.downloadFile(res, 'xml'); debugger;
this.xmlProcessing = false;
},
(err) => {
if (err.status === 401) {
// this.router.navigate(['unauthorized']);
} else {
this.xmlProcessing = false;
}
});
downloadFile(data, type) {
const fileName = 'test';
var contentType;
if (type === 'xml') {
contentType = 'text/xml';
}
var blob = new Blob([data._body], { type: contentType });
const dwldLink = document.createElement('a');
const url = URL.createObjectURL(blob);
const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1;
if (isSafariBrowser) {
dwldLink.setAttribute('target', '_blank');
}
const fullFileName = fileName + '.' + type;
dwldLink.setAttribute('href', url);
dwldLink.setAttribute('download', fullFileName);
dwldLink.style.visibility = 'hidden';
document.body.appendChild(dwldLink);
dwldLink.click();
document.body.removeChild(dwldLink);}
this is service.ts
postFile(value: any, fileToUpload: File, startDate) {
const formData: FormData = new FormData();
formData.append('File', fileToUpload, fileToUpload.name);
formData.append('ProcessingMode', value.processingMode);
formData.append('StartDate', '2015-05-23');
return this.http
.post(this.Url, formData);
}
and this is backend side:
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
try
{
var xml = Request.Form.Files["File"].ToString();
var httpRequest = HttpContext.Request.Form;
var postedFile = httpRequest.Files["File"];
string outputFile = Request.Form["info"].ToString();
var startDate = Request.Form["StartDate"];
var file = httpRequest.Files[0];
string fullPath = "";
string folderName = "Upload";
string antFile = #"C:\ant.bat";
string build = #"C:\build.xml";
string rootPath = #"C:\Users";
string newPath = Path.Combine(rootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return PhysicalFile(#"C:\Book1.xml", "application/xml", "Book1.xml");
}
catch (System.Exception ex)
{
return StatusCode(500);
}
}
I get error 500 and I do understand that the problem is with RequestHeaders but I can't figure out the way to solve it and in which side
for downloading for downloading any file... I am use this code in backend
and make and request the code from angular by normal http request
var myFile :: your file
if (System.IO.File.Exists (myFile.Path)) {// to know if the file is Exist or not
//Process File Here ...
} else {
return Json ("NotFound");
}
string contentType = "application/xml";
HttpContext.Response.ContentType = contentType;
var result = new FileContentResult (System.IO.File.ReadAllBytes (myFile.Path), contentType) {
FileDownloadName = $"{myFile.Title }" // + myFile.Extension
};
// System.IO.File.Delete (myFile.Path); //if you want to delete the file after download
return result;

Get Content-Disposition parameters

How do I get Content-Disposition parameters I returned from WebAPI controller using WebClient?
WebApi Controller
[Route("api/mycontroller/GetFile/{fileId}")]
public HttpResponseMessage GetFile(int fileId)
{
try
{
var file = GetSomeFile(fileId)
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(file));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = file.FileOriginalName;
/********* Parameter *************/
response.Content.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("MyParameter", "MyValue"));
return response;
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
Client
void DownloadFile()
{
WebClient wc = new WebClient();
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
wc.DownloadDataAsync(new Uri("api/mycontroller/GetFile/18"));
}
void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
WebClient wc=sender as WebClient;
// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
string fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", ""); //FileName ok
/****** How do I get "MyParameter"? **********/
}
var data = e.Result; //File OK
}
I'm returning a file from WebApi controller, I'm attaching the file name in the response content headers, but also I'd like to return an aditional value.
In the client I'm able to get the filename, but how do I get the aditional parameter?
If you are working with .NET 4.5 or later, consider using the System.Net.Mime.ContentDisposition class:
string cpString = wc.ResponseHeaders["Content-Disposition"];
ContentDisposition contentDisposition = new ContentDisposition(cpString);
string filename = contentDisposition.FileName;
StringDictionary parameters = contentDisposition.Parameters;
// You have got parameters now
Edit:
otherwise, you need to parse Content-Disposition header according to it's specification.
Here is a simple class that performs the parsing, close to the specification:
class ContentDisposition {
private static readonly Regex regex = new Regex(
"^([^;]+);(?:\\s*([^=]+)=((?<q>\"?)[^\"]*\\k<q>);?)*$",
RegexOptions.Compiled
);
private readonly string fileName;
private readonly StringDictionary parameters;
private readonly string type;
public ContentDisposition(string s) {
if (string.IsNullOrEmpty(s)) {
throw new ArgumentNullException("s");
}
Match match = regex.Match(s);
if (!match.Success) {
throw new FormatException("input is not a valid content-disposition string.");
}
var typeGroup = match.Groups[1];
var nameGroup = match.Groups[2];
var valueGroup = match.Groups[3];
int groupCount = match.Groups.Count;
int paramCount = nameGroup.Captures.Count;
this.type = typeGroup.Value;
this.parameters = new StringDictionary();
for (int i = 0; i < paramCount; i++ ) {
string name = nameGroup.Captures[i].Value;
string value = valueGroup.Captures[i].Value;
if (name.Equals("filename", StringComparison.InvariantCultureIgnoreCase)) {
this.fileName = value;
}
else {
this.parameters.Add(name, value);
}
}
}
public string FileName {
get {
return this.fileName;
}
}
public StringDictionary Parameters {
get {
return this.parameters;
}
}
public string Type {
get {
return this.type;
}
}
}
Then you can use it in this way:
static void Main() {
string text = "attachment; filename=\"fname.ext\"; param1=\"A\"; param2=\"A\";";
var cp = new ContentDisposition(text);
Console.WriteLine("FileName:" + cp.FileName);
foreach (DictionaryEntry param in cp.Parameters) {
Console.WriteLine("{0} = {1}", param.Key, param.Value);
}
}
// Output:
// FileName:"fname.ext"
// param1 = "A"
// param2 = "A"
The only thing that should be considered when using this class is it does not handle parameters (or filename) without a double quotation.
Edit 2:
It can now handle file names without quotations.
You can parse out the content disposition using the following framework code:
var content = "attachment; filename=myfile.csv";
var disposition = ContentDispositionHeaderValue.Parse(content);
Then just take the pieces off of the disposition instance.
disposition.FileName
disposition.DispositionType
With .NET Core 3.1 and more the most simple solution is:
using var response = await Client.SendAsync(request);
response.Content.Headers.ContentDisposition.FileName
The value is there I just needed to extract it:
The Content-Disposition header is returned like this:
Content-Disposition = attachment; filename="C:\team.jpg"; MyParameter=MyValue
So I just used some string manipulation to get the values:
void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
WebClient wc=sender as WebClient;
// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
string[] values = wc.ResponseHeaders["Content-Disposition"].Split(';');
string fileName = values.Single(v => v.Contains("filename"))
.Replace("filename=","")
.Replace("\"","");
/********** HERE IS THE PARAMETER ********/
string myParameter = values.Single(v => v.Contains("MyParameter"))
.Replace("MyParameter=", "")
.Replace("\"", "");
}
var data = e.Result; //File ok
}
As #Mehrzad Chehraz said you can use the new ContentDisposition class.
using System.Net.Mime;
// file1 is a HttpResponseMessage
FileName = new ContentDisposition(file1.Content.Headers.ContentDisposition.ToString()).FileName

Categories