C# WebClient.DownloadFile to specific path - c#

Hi i'm trying to download a png file and place it in a custom location and i have tried adding to the line but wc.DownloadFile does not allow 3 arguments. does anyone have a suggestion? (rookie programmer)
if i change wc.DownloadFile to wc.DownloadFileAsync it gives me an error on y[2]
string lookat = args[0];
string[] exploded = lookat.Split('/');
WebClient wc = new WebClient();
wc.Proxy = new WebProxy();
string content = wc.DownloadString(args[0]);
Regex rx = new Regex("data-id=\"(.*)\">");
MatchCollection matches = rx.Matches(content);
string uri = "http://" + exploded[2] + "/v2/photo/=";
string id = matches[0].ToString().Replace("\"", "").Replace(">", "").Replace("data-id=", "");
content = wc.DownloadString(uri + id);
string[] res = content.Split(new string[] { "filetobedownloaded_" }, StringSplitOptions.None);
foreach (string s in res)
{
if (s.Contains(".png"))
{
string[] y = s.Replace("\\", "").Split('"');
wc.DownloadFile(y[2], "filetobedownloaded_" + y[0].Replace("_png", ".jpg"));
}
}

The DownloadFileAsync accepts Uri and not string so you should convert your download link to Uri like this:
wc.DownloadFileAsync(new Uri(y[2]), "C:\\" + "filetobedownloaded_" + y[0].Replace("_png", ".jpg"));

Related

Read zip for photos with multiple photo file extensions using C#

I've created a method that reads .jpg files and displays them on my screen without extracting.
The var looks like this
var imageName = content.contentid + ".jpg";
content.contentid is too id number of the number + .jpg
But now I want that if there is, for example, a png or jfif file in the zip that it also just shows it.
How do I handle this in this method?
This is my code so far
private void getImage()
{
try
{
var folderName = "protocol-" + _protocol.id + "-" + _protocol.versionnr + ".zip";
var extractPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var zipPath = $"{extractPath}" + "/" + $"{folderName}";
var currentIndex = getCurrentIndex();
var content = _protocol.contents[currentIndex];
List<string> allowedExtensions = new List<string>() { "jpg", "png", "jfif" };
using (var archive = ZipFile.OpenRead(zipPath))
{
foreach (var pictureEntry in archive.Entries)
if (Path.GetFileNameWithoutExtension(pictureEntry.Name).Equals(content.contentid) && allowedExtensions.Contains(Path.GetExtension(pictureEntry.Name)))
{
byte[] buffer;
var length = pictureEntry.Length;
buffer = new byte[length];
pictureEntry.Open().Read(buffer, 0, (int)length);
myImage.Source = ImageSource.FromStream(() => new MemoryStream(buffer));
}
}
}
catch (Exception)
{
}
}
Well you can try this approach:
First define a List of extensions that you want to check against:
List<string> allowedExtensions = new List<string>() {"jpg", "png", "jfif" };
then change your if (pictureEntry.Name == imageName) for
if (Path.GetFileNameWithoutExtension(pictureEntry.Name) == content.contentid &&
allowedExtensions.Contains(Path.GetExtension(pictureEntry.Name)))
Also this line var imageName = content.contentid + ".jpg"; is innecesary as imageName didn't be used:

Trim off last directory/folder without using GetParent()

I am trying to emulate what "cd .." does, but without using Getparent().
input: /var/mobile/Documents/
actual output: /var/mobile/Documents/
desired output: /var/mobile/
public ArrayList JumpUpDirectory()
{
ArrayList directoryListing = new ArrayList();
StringBuilder storedPath = new StringBuilder();
foreach (var directories in storedPreviousDirectory.Split('/'))
{
storedPath.Append(directories + "/");
}
storedPath.Replace("//", "/");
directoryListing = iPhoneFileSystemBrowse(storedPreviousDirectory);
return directoryListing;
}
Try this:
string input = "/var/mobile/Documents/";
var parts = input.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries).ToList();
parts.RemoveAt(parts.Count - 1);
string output = string.Concat("/", string.Join("/", parts), "/");

Parsing the output of FtpWebRequest

I can see that there are 2 types of responses:
Windows
Unix
Examples
"08-25-12 06:52AM 139874418 3.03.06P13.12NB.rar"
"-r-xr-xr-x 1 owner group 1 Jun 3 1999 NotCurrentYear.txt"
I need to parse it and I used the following logic:
AnalyzedFolder folderToBeAnalyzed = new AnalyzedFolder();
folderToBeAnalyzed.Name = folder;
Job.AnalyzedFolders.Add(folderToBeAnalyzed);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(textBoxFTPSite.Text + folder);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(textBoxFTPUserName.Text, textBoxFTPPassword.Text);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string[] outputlines = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string info in outputlines)
{
var tokens = info.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string name;
string type;
string size;
DateTime dateModified;
string lsLine;
if (tokens.Length == 4) //WINDOWS
{
name = tokens[3];
if (tokens[2] == "<DIR>")
{
type = "D";
size = "";
}
else
{
type = "F";
size = tokens[2];
}
dateModified = DateTime.ParseExact(tokens[0] + " " + tokens[1], "MM-dd-yy h:mmtt", CultureInfo.InvariantCulture);
lsLine = info;
FTPFolderEntity entity = new FTPFolderEntity() { FolderName = folder, Name = name, Type = type, Size = size, DateModified = dateModified, LSLine = lsLine };
folderToBeAnalyzed.Entities.Add(entity);
}
else //UNIX
{
}
}
The problem is that for this file:
"11-15-12 10:02PM 324 Copy (10) of 1040.txt.zip"
because of the spaces, the logic fails. Also, like this bug, I suspect I may run into other problems also. Can anyone guide me for a better parsing method please ?
You can use a Regular Expression here to remove extra Whitesapces:
string info = "11-15-12 10:02PM 324 Copy (10) of 1040.txt.zip";
string result = Regex.Replace(info, #"\s\s+", " ");
After that you will get result as
// result = "11-15-12 10:02PM 324 Copy (10) of 1040.txt.zip";
ADDED, If you want to limit your tokens assuming the first is always the date, second is the time, and rest is your fileName or something:
var tokens = Regex.Split(info, #"\s+");
var newTokens = new string[]
{
tokens[0],
tokens[1],
tokens[2],
tokens[3] + ' ' + tokens[4] + ' ' + tokens[5] + ' ' + tokens[6]
};
You could do a split using a Regex.
var tokens = Regex.Split(info, #"\s+");

How to Replace the String in C#?

I have the string string test="http://www.test.com//web?testid=12".
I need to replace with in the string // into /.
Problem is if I use string a=test.replace("//","/") I get http:/www.test.com/web?testid=12 all with single slash(/) but I need http://www.test.com/web?testid=12.
I need only the second // nearby web, not first // near by www.
How to do this?
You can make second replace
string test="http://www.test.com//web?testid=12";
string a=test.Replace("//","/").Replace("http:/","http://");
=)
string test = #"http://www.test.com//web?testid=12";
test = test.Substring(0, test.LastIndexOf(#"//") - 1)
+ test.Substring(test.LastIndexOf(#"//")).Replace(#"//", #"/");
Or since its a Uri, you can do:
Uri uri = new Uri(test);
string newTest = uri.Scheme + #"//" + uri.Authority
+ uri.PathAndQuery.Replace(#"//",#"/");
string test="http://www.test.com//web?testid=12"
string[] test2 = test.Split('//');
string test = test2[0] + "//" + test2[1] + "/" + test2[2];
Regex.Replace(test, "[^:]//", "/");
you can use stringbuilder as well.
StringBuilder b =new StringBuilder();
b.Replace("/","//",int startindex,int count);
Simply remove one of the last slashes with String.Remove():
string test="http://www.test.com//web?testid=12";
string output = test.Remove(test.LastIndexOf("//"), 1);
var http = "http://someurl//data";
var splitindex = http.IndexOf("/") + 1;
var res = http.Substring(splitindex+1, (http.Length-1) - splitindex).Replace("//","/");
http = "http://" + res;
Or
StringBuilder strBlder = new StringBuilder();
strBlder.Append("http://someurl//data");
//use the previously used variable splitindex
strBlder.Replace("//", "/", splitindex + 1, (http.Length) - splitindex);

Get file name from URI string in C#

I have this method for grabbing the file name from a string URI. What can I do to make it more robust?
private string GetFileName(string hrefLink)
{
string[] parts = hrefLink.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = hrefLink;
return fileName;
}
You can just make a System.Uri object, and use IsFile to verify it's a file, then Uri.LocalPath to extract the filename.
This is much safer, as it provides you a means to check the validity of the URI as well.
Edit in response to comment:
To get just the full filename, I'd use:
Uri uri = new Uri(hreflink);
if (uri.IsFile) {
string filename = System.IO.Path.GetFileName(uri.LocalPath);
}
This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.
Uri.IsFile doesn't work with http urls. It only works for "file://".
From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile."
So you can't depend on that.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
Most other answers are either incomplete or don't deal with stuff coming after the path (query string/hash).
readonly static Uri SomeBaseUri = new Uri("http://canbeanything");
static string GetFileNameFromUrl(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
uri = new Uri(SomeBaseUri, url);
return Path.GetFileName(uri.LocalPath);
}
Test results:
GetFileNameFromUrl(""); // ""
GetFileNameFromUrl("test"); // "test"
GetFileNameFromUrl("test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d"); // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/"); // ""
The accepted answer is problematic for http urls. Moreover Uri.LocalPath does Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath
The correct way to do this for http urls is:
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
I think this will do what you need:
var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(hrefLink.Replace("/", "\\"));
}
THis assumes, of course, that you've parsed out the file name.
EDIT #2:
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}
This should handle spaces and the like in the file name.
As of 2020, handles query strings & encoded URLs
public static string GetFileNameFromUrl (string url)
{
var decoded = HttpUtility.UrlDecode(url);
if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
{
decoded = decoded.Substring(0, queryIndex);
}
return Path.GetFileName(decoded);
}
this is my sample you can use:
public static string GetFileNameValidChar(string fileName)
{
foreach (var item in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(item.ToString(), "");
}
return fileName;
}
public static string GetFileNameFromUrl(string url)
{
string fileName = "";
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
}
string ext = "";
if (!string.IsNullOrEmpty(fileName))
{
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
return GetFileNameValidChar(fileName + ext);
}
fileName = Path.GetFileName(url);
if (string.IsNullOrEmpty(fileName))
{
fileName = "noName";
}
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
fileName = fileName + ext;
if (!fileName.StartsWith("?"))
fileName = fileName.Split('?').FirstOrDefault();
fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
return GetFileNameValidChar(fileName);
}
Usage:
var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");
Simple and straight forward:
Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
fileName = Path.GetFileName(uri.LocalPath);
//First Method to get fileName from fileurl
List<string> fileNameListValues = new List<string>();
//fileNameListValues List consist of fileName and fileUrl
//we need to get fileName and fileurl from fileNameListValues List
name
foreach(var items in fileNameListValues)
{
var fileUrl = items;
var uriPath = new Uri(items).LocalPath;
var fileName = Path.GetFileName(uriPath);
}
//Second Way to get filename from fileurl is ->
fileNameValue = "https://projectname.com/assets\UploadDocuments\documentFile_637897408013343662.jpg";
fileName = " documentFile_637897408013343662.jpg";
//way to get filename from fileurl
string filename =
fileNameValue.Substring(fileNameValue.LastIndexOf("\\") + 1);

Categories

Resources