So let's say I have a download url that when you GET it, it downloads a file.
Now, this file is not a txt or anything, it has no extension.
How would I code a GET request to the URL, but make it download to a certain path?
EDIT: Also, how would I convert it to a TXT and read from the txt afterwards?
NOTE: It's a get request site that instantly downloads the file, not a file on a site you can open in your browser
EDIT 2: It actually returns xml, not the file, sorry
just using a browser downloads it.
What is the real content of that file?
You can try to configure the content-type as "application/octet-stream".
It asks the server for byte content.
If the content is regular text already, you can simply add ".txt" to the file name and you can read it whenever you want.
You do it like this it shouldn't matter if your link has a clear ending like the one I have used. Or if you are really serious about making the GET part explicit use RestSharp. Look now you can even change the file extensions from within the code not that it would matter the least bit. I tossed in some Linq2Xml since you mentioned your file was xml and I thought you possible needed to do something with it.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Xml.Linq;
using System.Linq;
using RestSharp;
namespace Get2File
{
internal class Program
{
private const string FallbackUrl = #"https://gist.github.com/Rusk85/8d189cd35295cfbd272d8c2121110e38/raw/4885d9ba37528faab50d9307f76800e2e1121ea2/example-xml-with-embedded-html.xml";
private string _downloadedContent = null;
private const string FileNameWithoutExtension = "File";
private static void Main(string[] args)
{
var p = new Program();
p.Get2FileWithRestSharp(fileExtensions:".xml");
p.UseLinq2XmlOnFile();
}
private void Get2File(string altUrl = null, string fileExtensions = ".txt")
{
var url = !string.IsNullOrEmpty(altUrl)
? altUrl
: FallbackUrl;
var client = new HttpClient();
var content = client.GetStringAsync(url).Result;
_downloadedContent = content;
var outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{FileNameWithoutExtension}{fileExtensions}");
File.WriteAllText(outputPath, content);
}
private void Get2FileWithRestSharp(string altUrl = null, string fileExtensions = ".txt")
{
var url = !string.IsNullOrEmpty(altUrl)
? altUrl
: FallbackUrl;
var urlAsUri = new Uri(url);
var client = new RestClient(urlAsUri);
var request = new RestRequest(Method.GET);
var content = string.Empty;
var result = client.Execute(request);
content = result.Content;
_downloadedContent = content;
var output = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{FileNameWithoutExtension}{fileExtensions}");
File.WriteAllText(output, content);
}
private void UseLinq2XmlOnFile()
{
XElement xElement = XElement.Parse(_downloadedContent);
var elements = xElement.Elements();
var StringElement = elements.FirstOrDefault(e => e.Name == "String");
var tranlateXAttribute = StringElement.Attributes().FirstOrDefault(attr => attr.Name == "translate");
Debug.WriteLine(tranlateXAttribute.Value);
}
}
}
Related
I have this problem when I'm trying to read JSON file (or any file): It's not able to find that file. I try everything, even the absolute path (error almost same - DirectoryNotFound)
This is structure of mine code:
And this is code:
private void LoadJson()
{
using (var r = new StreamReader("quizQuestions.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Questions>>(json);
}
}
I I even try to use Directory.GetCurrentDirectory() but it's returning : / -> only this character. I don't know where is a mistake or if I forgot to set something. I try to find answers everywhere but I was not able to find anything with this.
Make sure the Build Action of the file is set as Content or as an Asset and give this a try.
private void LoadJson()
{
AssetManager assets = this.Assets;
using (var r = new StreamReader(assets.Open ("quizQuestions.json")))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Questions>>(json);
}
}
You can configure the file as Embedded Resource and then access it like this:
public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
var resourceNames = assembly.GetManifestResourceNames();
var resourcePaths = resourceNames
.Where(x => x.EndsWith(resourceFileName, StringComparison.CurrentCultureIgnoreCase)).ToArray();
if (resourcePaths.Any() && resourcePaths.Count() == 1)
{
return assembly.GetManifestResourceStream(resourcePaths.Single());
}
return null; // or throw Exception
}
private void LoadJson()
{
Assembly assembly = GetAssemblyContainingTheJson();
using (var r = GetEmbeddedResourceStream(assembly, "quizQuestions.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Questions>>(json);
}
}
I'm trying to convert Text To audio using Google.Cloud.TextToSpeech.V1. it works fine but I do not know how can I Specify an audio profile to use using c# while I found code in Node.js and python But Not anything in c# this is my code
static void Main(string[] args)
{
List<Word> lst = IntialData();
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", #"C:\Users\Admin\TextToSpeechApiDemo\key.json");
var client = TextToSpeechClient.Create();
// The input to be synthesized, can be provided as text or SSML.
foreach (Word item in lst)
{
var input = new SynthesisInput
{
Text = item.Name,
};
// Build the voice request.
var voiceSelection = new VoiceSelectionParams
{
LanguageCode = "ar",
//SsmlGender = SsmlVoiceGender.Female,
Name = "ar-XA-Wavenet-A"
};
// Specify the type of audio file.
var audioConfig = new AudioConfig
{
AudioEncoding = AudioEncoding.Linear16,
};
// Perform the text-to-speech request.
var response = client.SynthesizeSpeech(input, voiceSelection, audioConfig);
// Write the response to the output file.
using (var output = File.Create(#"E:\Noursound\sim\ar-XA-Wavenet-A\" + item.Id.ToString() + ".wav"))
{
response.AudioContent.WriteTo(output);
}
}
}
I found this code in python he set effects_profile_id
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3,
effects_profile_id=[effects_profile_id],
How can i do that using c#
The problem was in the version on the NuGet package i used 1.0.0-beta01 , and it's not have the EffectsProfileId property but after update it to version to Google.Cloud.TextToSpeech.V1 version 2.3.0 i found the property.
using Google.Cloud.TextToSpeech.V1;
class Program
{
static void Main(string[] args)
{
var config = new AudioConfig
{
AudioEncoding = AudioEncoding.Mp3,
EffectsProfileId = { "your profile ID" }
};
}
}
i created git issue for that on github Here's a link!
below is C# WEB API Code to generate Excel :
public class FileExportController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var callerContext = CallerContext.DefaultCallerContext;
ReportingInput userInput = new ReportingInput();
userInput.ClientOneCode = "AVON";
string handle = Guid.NewGuid().ToString();
var #event = new GetJobReprotDataBlEvent(callerContext, userInput);
WebApiApplication.ApplicationInitializerObj.EventBus.Publish(#event);
XLWorkbook wb = new FileExportEngine().ExportExcel(#event.ReportData); //this is returning XLWorkbook
string fileName = "JobReport_" + DateTime.Now.ToString("yyyy -MM-dd HH':'mm':'ss") + ".xlsx";
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
When I call this API from browser, I am able to generate excel file.
http://localhost/ETLScheduler/api/FileExport -- this is working when hit direct in browser
Now I want to use consume this API in angular 5 application.I have a button.On click button I call the component method downloadFile() to download the file.
Below is the code :
downloadReport() {
this._service.downloadJobReport('AVON');
}
where downloadJobReport() is in my service file as below :
downloadJobReport(clientCode: string) {
return this._http.get(APIs.downloadJobReport);
}
When I am running the application and click on Download button, I am getting nothing, I mean file is not downloading. Can anyone have idea,how should I update my angular code to consume the API.
Thanks in advance.
As you mentioned above in comments you are using below angular code to download file:
downloadFile(data: Blob) {
const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const blob = new Blob([data], { type: contentType });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
As I also have tried this code, it is working in chrome browser but not working in IE and edge.
You may update your method somthing like below:
var downloadFile=function (file_name, content) {
var csvData = new Blob([content], { type: 'text/csv' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
window.navigator.msSaveOrOpenBlob(csvData, file_name);
} else { // for Non-IE (chrome, firefox etc.)
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var csvUrl = URL.createObjectURL(csvData);
a.href = csvUrl;
a.download = file_name;
a.click();
URL.revokeObjectURL(a.href)
a.remove();
}
};
you can refer below link for more information:
Open links made by createObjectURL in IE11
Problem is, that Angular expects JSON as a result. You need to configure your GET request so, that it expects something different.
public downloadJobReport(clientCode: string)): Observable<Blob> {
return this._http.get(APIs.downloadJobReport, { responseType: 'blob' });
}
Just a tiny question, you pass an argument clientCode to the downloadJobReport, but never use it. Maybe wise to leave that out?
I am trying to make a parser based on "AngleSharp".
I use the following code for download:
var itemsAttr = document.QuerySelectorAll("img[id='print_user_photo']");
string foto_url = itemsAttr[0].GetAttribute("src");
string path = pathFolderIMG + id_source + ".jpg";
WebClient webClient = new WebClient();
webClient.DownloadFile(foto_url, path);
For pages "type_1" -link - the code works.
For pages "type_2" - link - the code does not work.
How to download photos for pages "type_2"?
Please read the AngleSharp documentation carefully, e.g., looking at the FAQ we get:
var imageUrl = #"https://via.placeholder.com/150";
var localPath = #"g:\downloads\image.jpg";
var download = context.GetService<IDocumentLoader>().FetchAsync(new DocumentRequest(new Url(imageUrl)));
using (var response = await download.Task)
{
using (var target = File.OpenWrite(localPath))
{
await response.Content.CopyToAsync(target);
}
}
where we used a configuration like
var config = Configuration.Default.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }).WithCookies();
var context = BrowsingContext.New(config);
I'm trying to display a local pdf file using a custom LocalSchemeHandler which reads a memory stream from the file.
The file exists and the memory stream is being read properly. But there is nothing being displayed in the browser window. Displaying the same file via file scheme works.
ResourceHandler:
public class LocalSchemeHandler : ResourceHandler
{
public override bool ProcessRequestAsync(IRequest request, ICallback callback)
{
var uri = new Uri(request.Url);
var file = uri.AbsolutePath;
Task.Run(() =>
{
using (callback)
{
if (!File.Exists(file))
{
callback.Cancel();
return;
}
byte[] bytes = File.ReadAllBytes(file);
var stream = new MemoryStream(bytes);
if (stream == null)
{
callback.Cancel();
}
else
{
stream.Position = 0;
ResponseLength = stream.Length;
var fileExtension = Path.GetExtension(file);
MimeType = GetMimeType(fileExtension);
StatusCode = (int)HttpStatusCode.OK;
Stream = stream;
callback.Continue();
}
}
});
return true;
}
}
ISchemeHandlerFactory:
public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "local";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new LocalSchemeHandler();
}
}
Settings:
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory()
});
// Increase the log severity so CEF outputs detailed information, useful for debugging
settings.LogSeverity = LogSeverity.Default;
Cef.Initialize(settings);
EDIT
Trying to display the PDF file via ResourceHandler.FromFilePath also doesn't work (nothing is displayed).
public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "local";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
var uri = new Uri(request.Url);
var file = uri.AbsolutePath;
var fileExtension = Path.GetExtension(file);
var mimeType = ResourceHandler.GetMimeType(fileExtension);
return ResourceHandler.FromFilePath(file, mimeType);
}
}
EDIT2
After setting LogSeverity to Default the log says: [0524/150955.108:INFO:CONSOLE(20)] "Refused to load plugin data from 'local://c/Users/abidh/Desktop/pdf.pdf' because it violates the following Content Security Policy directive: "object-src * blob: externalfile: file: filesystem: data:".
Didn't find a solution using google. Thanks to amaitland, using the IsCSPBypassing property solved the problem:
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory(),
IsCSPBypassing = true
});
settings.LogSeverity = LogSeverity.Error;
Cef.Initialize(settings);
Set the PDF file path to ChromiumWebBrowser.Address as format like file:///C:/Users/xxx/yyy.pdf, the CEFSharp will render PDF just like Chrome browser.