c# - Migrate code from WebClient to HTTPClient - c#

if (FileExtension == ".txt")
{
string enumLines = File.ReadAllText(FoundPics, Encoding.UTF8);
Clipboard.SetText(enumLines);
using (WebClient client = new())
{
DirectoryInfo di = new DirectoryInfo(FoundPics);
client.DownloadFile(enumLines, FolderPath + #"\" + "Template.gif");
Image gifTemplate = Image.FromFile(FolderPath + #"\" + "Template.gif");
pictureBox.Image = gifTemplate;
}
}
I have this code that retrieves a url from a txt file, downloads a .gif from it and sets it to the picturebox
However it's using Webclient that I was recommended to avoid.
I'm trying to change to HTTPClient now but I'm really lost.
Can someone provide some pseudo code so that I can figure out what to do?

var data = await client.GetByteArrayAsync(FolderPath + #"\" + "Template.gif");
File.WriteAllBytes(#"\path\to\downloads\Template.gif", data);
FolderPath must be a uri
Your application must have write access to the downloads folder

Related

“The given path's format is not supported.”

I am trying to create a PDF via C# using iTextSharp
if (emp.FormDesc == "FormOne")
{
string filePath = #"\\G:\SharedDrive\Forms\FormOne\" + filename;
// Write out PDF from memory stream.
using (FileStream fs = File.Create(filePath))
{
fs.Write(content, 0, (int)content.Length);
}
}
I am returning this string
filePath = "\\\\G:\\SharedDrive\\Forms\\FormOne\\11-23-2020.pdf"
but I keep getting the error message “The given path's format is not supported.”
Any ideas? My syntax seems correct.
Thank you.
Change this:
string filePath = #"\\G:\SharedDrive\Forms\FormOne\" + filename;
To this:
string filePath = #"G:\SharedDrive\Forms\FormOne\" + filename;
Or if it is a network share, then something like this:
string filePath = #"\\SharedDrive\Forms\FormOne\" + filename;
where "SharedDrive" is the name of the network share.
(edited in response to first comment below)
The better and saffer way is using Path.Combine like below:
string filePath = Path.Combine("G:\SharedDrive\Forms\FormOne", filename);

How to convert PDF Base64 into pdf then PDF into an image in C#

following is the code added:
The image object is in the library.imaging.
"using System.Drawing;"
"using System.Drawing.Imaging;"
{
byte[] b = Convert.FromBase64String("R0lGODlhAQABAIAAA");
Image image;
using (MemoryStream memstr = new MemoryStream(b))
{
image = Image.FromStream(memstr);
}
}
Here is the new code I'm working on:
{
string base64BinaryStr = " ";
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
string s = Encoding.UTF8.GetString(PDFDecoded);
}
So this is your current code:
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
You don't actually need BinaryWriter for this. File.Create already gives you a FileStream:
FileStream writer = File.Create(FileName + ".pdf");
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
But this will still have the problem you're experiencing because you're not flushing the data to it. We also need to close the file. Thankfully, we can wrap it in using and it will do both for us:
using (FileStream writer = File.Create(FileName + ".pdf"))
{
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
}
But a simpler way to do this is:
File.WriteAllBytes(FileName + ".pdf", PDFDecoded);
As for PDF -> Image, you'll probably have to see if there is a library available for this (search "PDF to Image NuGet") that can help you with this as I don't think there is anything built-in.
Just a thought, you don't need to create a physical PDF file, you can have it in memory and convert it to image from there.
Now the problem is that you cannot use Image from System.Drawing.Imaging for this, it doesn't support reading PDF file.
Instead you'll need to search for some library that can do that.
For example, try GemBox.Pdf, you can use it like this:
string base64String = "...";
byte[] pdfBytes = Convert.FromBase64String(base64String);
using (PdfDocument pdfDocument = PdfDocument.Load(new MemoryStream(pdfBytes)))
{
ImageSaveOptions imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);
string imageName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm") + ".png";
pdfDocument.Save(#"C:\Users\Downloads\" + imageName, imageOptions);
}
I've used the code provided on this Convert example.

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;
}

UnauthorizedAccessException when Creating file

I have this code that downloads file from ftp server and then it creates that file in path that is set.
string inputfilepath = #"C:\Users\me\Documents\Test";
string ftphost = "ftp_server";
string ftpfilepath = #"/TestDOTNET/text.TXT";
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
using (WebClient request = new WebClient())
{
request.Proxy = null;
request.Credentials = new NetworkCredential("user", "pass");
byte[] fileData = request.DownloadData(ftpfullpath);
File.SetAttributes(inputfilepath, FileAttributes.Normal);
using (FileStream file = File.Create(inputfilepath)) // this is the line where I get the exception
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
MessageBox.Show("Download Complete");
}
I tried to create app.manifest and set requestedExcetuion level to requireAdministrator but still got no change.
Thank you for your time
Are you sure the user running the app has write-access to the file system?
You should check that the effective user running the app - which is usually a different user (eg. NETWORK SERVICE user) from yourself - has the appropriate rights.
Check on IIS application pool settings which is the user running the app
Assign appropriate rights to such user on your target folder
You should first test for the Directory Path if it exists or not, if yes, then negate the read-only attribute for that directory. If not, then create directory and then create the test.txt to write in it.
Ex::
string inputdirpath = #"C:\Users\me\Documents\Test";
string inputfilepath = inputdirpath + "\text.TXT";
// Downloading Stuff
if(Directory.Exists(inputdirpath ))
{
var di = new DirectoryInfo("inputfilepath ");
di.Attributes &= ~FileAttributes.ReadOnly;
using (FileStream file = File.Create(inputfilepath))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
MessageBox.Show("Download Complete");
}
else
{
// Create Directory
// Set Attributes
// Create file
// Write data
}

File upload in asp.net 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.

Categories