I'm using google map API. I have 4 destinations and I want to get their locations ordered by nearest location first followed by second nearest. I have to show on Google Map which location is 1st being the nearest and then the next nearest and so on. So far I have only successfully calculated the distance between 2 locations by using below code:
private void button1_Click(object sender, EventArgs e)
{
getDistance("DECATUR FARM ROAD CHICHESTER PO20 8JT", "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW");
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
//string from = origin.Text;
//string to = destination.Text;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
//string requesturl = #"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false";
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
return distance;
//ResultingDistance.Text = distance;
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
How do I show the destinations according to their distance on google map. Any tip or pointers will be appreciated.
Please see the image, this is what I am trying to accomplish
Happy :) Enjoy Coding..
ArrayList arraylist;
List<string> adddistance = new List<string>();
List<string> getfinallist = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
string s = "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW,PINETOP BIRKLANDS LANE ST ALBANS AL1 1EE,HOLYWELL HILL ST ALBANS AL1 1BT,OLD RECTORY HOLYWELL HILL ST ALBANS AL1 1BY";
button("DECATUR FARM ROAD CHICHESTER PO20 8JT", s);
}
public void button(string orign , string destination)
{
string[] words = destination.Split(',');
foreach (string word in words)
{
getDistance(orign, word);
}
sorting();
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
string strdistance = (string)o.SelectToken("routes[0].legs[0].distance.value") + " , " + destination + " , ";
adddistance.Add(strdistance);
return distance;
}
public void sorting()
{
adddistance.Sort();
string getfirststring = adddistance.FirstOrDefault().ToString() ;
var vals = getfirststring.Split(',')[1];
getfinallist.Add(getfirststring.Split(',')[1]);
StringBuilder builder = new StringBuilder();
adddistance.RemoveAt(0);
foreach (string cat in adddistance) // Loop through all strings
{
builder.Append(cat); // Append string to StringBuilder
}
adddistance.Where((wors, index) => index % 2 == 0);
string result = builder.ToString();
string[] words = result.Split(',');
string[] even = words.Where((str, ix) => ix % 2 == 1).ToArray();
adddistance.Clear();
foreach (string word in even)
{ //string get = Regex.Match(word, #"^[" + numSet + #"]+$").ToString();
if (word != " ")
{
getDistance(vals, word);
}
}
sorting();
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
Related
I am writing on my pdf-word converter and I just received a really strange exception witch makes no sens to me.
Error:PdfiumViewer.PdfException:{"Unsupported security scheme"}
Its the first time that such a exception appears. but I have to be honest that I never tried to convert more then 3-4 files from pdf to word and right now I am doing more then 100 files.
Here is my code I am sry if its too long but I simply do not know on which line the error occurs
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
string path = #"C:\Users\chnikos\Desktop\Test\Batch1\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
var doc = application.Documents.Add();
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\chnikos\Desktop\Test\Batch1\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
.....
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
string imagePath = #"C:\Users\chnikos\Desktop\Test\Batch1\";
Array.ForEach(Directory.GetFiles(imagePath, "*.png"), delegate(string deletePath) { File.Delete(deletePath); });
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
}
I'm developing an application that reads a xml file folder , and each file it to do some checks and copied to a new folder based on some criteria.
But memory usage continues to grow when it arrives in the foreach loop , and I believe that should not happen , because the variables do not increase at each iteration , are only overwritten.
Here is my code:
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
namespace XMLOrganizer
{
public partial class Form1 : Form
{
string selectedFolder;
public Form1()
{
InitializeComponent();
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
selectedFolder = folderBrowserDialog1.SelectedPath;
organizeBtn.Enabled = true;
}
private void organizeBtn_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Selecione o tipo de nota", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
return;
}
if (comboBox1.SelectedIndex != 2)
{
OrganizeXml(label2, selectedFolder, comboBox1);
}
//ORGANIZAR LOTES
else
{
string folder = selectedFolder;
label2.Text = "Arquivos sendo processados, aguarde...";
label2.Refresh();
string[] files = Directory.GetFiles(folder, "*.xml", SearchOption.AllDirectories);
int atualFile = 1, totalXML = files.Length;
foreach (string file in files)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(file);
XmlNodeList enviNFe = xmlDocument.GetElementsByTagName("enviNFe");
string versao = ((XmlElement)enviNFe[0]).Attributes["versao"].Value;
XmlNodeList NFe = ((XmlElement)enviNFe[0]).GetElementsByTagName("NFe");
Directory.CreateDirectory(selectedFolder + #"\NOTAS");
label2.Text = "Processando arquivo " + atualFile + " de " + totalXML;
string notaXML;
foreach (XmlElement nota in NFe)
{
notaXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"" + versao + "\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + nota.OuterXml + "</nfeProc>";
XmlNodeList infNFe = nota.GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
File.WriteAllText(selectedFolder + "\\NOTAS\\" + chave + ".xml", notaXML);
}
}
OrganizeXml(label2, selectedFolder + "\\NOTAS", comboBox1);
}
}
private static void OrganizeXml(Label label2, string selectedFolder, ComboBox comboBox1)
{
string folderMove = String.Empty;
string folder = selectedFolder;
label2.Text = "Arquivos sendo processados, aguarde...";
label2.Refresh();
string[] files = Directory.GetFiles(folder, "*.xml", SearchOption.AllDirectories);
int i = 1, arquivos = files.Length;
Directory.CreateDirectory(folder + #"\ORGANIZADO");
if (comboBox1.SelectedIndex != 2)
{
Directory.CreateDirectory(folder + #"\ORGANIZADO\OUTROS");
Directory.CreateDirectory(folder + #"\ORGANIZADO\LOTES");
}
foreach (string file in files)
{
XmlDocument xmlDocument = new XmlDocument();
try
{
xmlDocument.Load(file);
if (xmlDocument.DocumentElement.Name != "nfeProc")
{
XmlNodeList NFe = xmlDocument.GetElementsByTagName("NFe");
var nota = ((XmlElement) NFe[0]);
if (nota != null)
{
XmlNodeList infNFe = ((XmlElement) NFe[0]).GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
string versao = infNFe[0].Attributes["versao"].Value;
string notaXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"" + versao +
"\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + nota.OuterXml +
"</nfeProc>";
string dirNote = Path.GetDirectoryName(file);
File.WriteAllText(dirNote + "\\fix_" + chave + ".xml", notaXML);
}
}
//
//
//
}
catch (XmlException)
{
XmlDocument doc = new XmlDocument();
string arquivo = ReadFileToString(file);
arquivo = RemoveSpecialCharacters(arquivo);
if (arquivo == "")
{
File.Move(file, folder + #"\ORGANIZADO\OUTROS\corrupt_" + Path.GetFileName(file));
continue;
}
try
{
doc.LoadXml(arquivo);
doc.PreserveWhitespace = true;
doc.Save(file);
}
catch (XmlException)
{
File.Move(file, folder + #"\ORGANIZADO\OUTROS\corrupt_" + Path.GetFileName(file));
files = files.Where(f => f != file).ToArray();
}
}
}
foreach (string file in files)
{
string arquivoLoad = file;
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(arquivoLoad);
XmlNodeList NFe = xmlDocument.GetElementsByTagName("NFe");
XmlNodeList enviNFe = xmlDocument.GetElementsByTagName("enviNFe");
if (NFe.Count == 0)
{
if (File.Exists(folder + #"\ORGANIZADO\OUTROS\no_NFe_" + Path.GetFileName(arquivoLoad)))
{
Random rnd = new Random();
File.Copy(arquivoLoad,
folder + #"\ORGANIZADO\OUTROS\no_NFe_" + rnd.Next(1, 5000) + Path.GetFileName(arquivoLoad));
}
else
{
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\OUTROS\no_NFe_" + Path.GetFileName(arquivoLoad));
}
continue;
}
XmlNodeList infNFe = ((XmlElement)NFe[0]).GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
if (xmlDocument.DocumentElement.Name != "nfeProc")
{
File.Move(arquivoLoad, folder + #"\ORGANIZADO\OUTROS\no_nfeProc_" + Path.GetFileName(arquivoLoad));
arquivoLoad = Path.GetDirectoryName(file) + "\\fix_" + chave + ".xml";
}
if (enviNFe.Count > 0)
{
if (File.Exists(folder + #"\ORGANIZADO\LOTES\" + Path.GetFileName(arquivoLoad)))
{
Random rnd = new Random();
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\LOTES\" + rnd.Next(1, 5000) + Path.GetFileName(arquivoLoad));
}
else
{
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\LOTES\" + Path.GetFileName(arquivoLoad));
}
continue;
}
//XmlNodeList infNFe = ((XmlElement)NFe[0]).GetElementsByTagName("infNFe");
XmlNodeList ide = ((XmlElement)infNFe[0]).GetElementsByTagName("ide");
string tpNF = ((XmlElement)ide[0]).GetElementsByTagName("tpNF")[0].InnerText;
//if (tpNF == "0") continue;
XmlNodeList emit = ((XmlElement)infNFe[0]).GetElementsByTagName("emit");
string emitInfoCod;
if (((XmlElement)emit[0]).GetElementsByTagName("CNPJ").Count > 0)
{
emitInfoCod = ((XmlElement)emit[0]).GetElementsByTagName("CNPJ")[0].InnerText;
}
else if (((XmlElement)emit[0]).GetElementsByTagName("CPF").Count > 0)
{
emitInfoCod = ((XmlElement)emit[0]).GetElementsByTagName("CPF")[0].InnerText;
}
else
{
emitInfoCod = "0";
}
string ide_dEmi = (((XmlElement)ide[0]).GetElementsByTagName("dEmi").Count > 0)
? ((XmlElement)ide[0]).GetElementsByTagName("dEmi")[0].InnerText
: ((XmlElement)ide[0]).GetElementsByTagName("dhEmi")[0].InnerText;
string[] data = ide_dEmi.Split('-');
string folderName = data[0] + "\\" + data[1];
string organizeStyle = String.Empty;
if (comboBox1.SelectedIndex == 0 || comboBox1.SelectedIndex == 2)
{
organizeStyle = folder + #"\ORGANIZADO\" + emitInfoCod + #"\" + folderName;
}
else
{
organizeStyle = folder + #"\ORGANIZADO\" + folderName + #"\" + emitInfoCod;
}
if (!Directory.Exists(organizeStyle))
{
Directory.CreateDirectory(organizeStyle);
}
folderMove = organizeStyle + "\\";
if (!File.Exists(folderMove + chave + ".xml"))
{
File.Copy(arquivoLoad, folderMove + chave + ".xml");
}
label2.Text = "Arquivos sendo processados, aguarde... (" + i + " / " + arquivos + ")";
label2.Refresh();
i++;
}
label2.Text = "Notas organizadas com sucesso!";
label2.Refresh();
}
public static string ReadFileToString(string filePath)
{
using (StreamReader streamReader = new StreamReader(filePath))
{
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, #"[^\u0000-\u007F]", string.Empty);
}
private void exitBtn_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
How can I determine what 's going on?
The value of a variable pointing to a reference type is not the object at all, its just the memory address where the object lives.
So when you do the following:
while (true)
{
var myVariable = new MyReferenceType();
}
The only memory you are really reusing is the variable itself (think of a 32 or 64 bit pointer). But on every iteration your are allocating somewhere in memory space enough to fit the new object you've just created and that memory is most definitely not the memory reserved to the previous object.
This is essentially why your memory usage is growing. The "old" objects of previous iterations with no live reference will eventually get collected by the GC, but that could be never if the GC decides that it has enough memory available to avoid it.
I've made a console app (don't judge for it being badly written, I can't even do classes properly and I know that RegEx doesn't work with XML/HTML, but let's not mind that I'm not even a programmer)
int retryCount = 0;
int retryCount02 = 0;
int innerpercentage = 1;
HttpWebResponse response = null;
HttpWebResponse response02 = null;
//WebRequest groupingurl = WebRequest.Create("supersecretlink");
WebRequest groupingurl = WebRequest.Create("anothersupersecretlink"); // temp
var groupingurlread = (HttpWebResponse)groupingurl.GetResponse();
using (var groupingreader = new StreamReader(groupingurlread.GetResponseStream(), Encoding.ASCII))
{
string responseGrouping = groupingreader.ReadToEnd();
Console.WriteLine("--------");
var pattern = #"""ClassID"" Value=""(.*?)""";
var matches = Regex.Matches(responseGrouping, pattern)
.OfType<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();
int percentage = 1;
int percentagedone = matches.Length;
foreach (string r in matches)
{
while (true)
{
try
{
var url = "themostseriouslinkever";
string req = File.ReadAllText(#"somanylinksrighthere", Encoding.Default);
var go = url + req;
go = String.Format(go, r);
WebRequest request = WebRequest.Create(go);
response = (HttpWebResponse)request.GetResponse();
break;
}
catch (WebException)
{
Console.WriteLine("Retry No. {0}", retryCount+1);
if (++retryCount < 3) continue;
throw;
}
}
retryCount = 0;
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
string responseText = reader.ReadToEnd();
pattern = #"<PartNumber>(.*?)</PartNumber>";
matches = Regex.Matches(responseText, pattern)
.OfType<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();
int innerpercentagedone = matches.Length;
foreach (string bbb in matches)
{
// -----
//Console.WriteLine(bbb);
while (true)
{
try
{
var url02 = "anothersecret";
string req02 = File.ReadAllText(#"seeecreet", Encoding.Default);
var go02 = url02 + req02;
go02 = string.Format(go02, bbb);
WebRequest request02 = WebRequest.Create(go02);
response02 = (HttpWebResponse)request02.GetResponse();
break;
}
catch (WebException)
{
Console.WriteLine("Retry No. {0}", retryCount02+1);
if (++retryCount02 < 3) continue;
throw;
}
}
retryCount02 = 0;
using (var reader02 = new StreamReader(response02.GetResponseStream(), Encoding.ASCII))
{
string responseText02 = reader02.ReadToEnd();
responseText02 = Regex.Replace(responseText02, (#"<\?xml.*\?>"), "");
//Console.WriteLine(responseText02);
//Console.WriteLine("</PartNumber>.*<");
responseText = Regex.Replace(responseText, ((#"<PartNumber>" + bbb + #"<\/PartNumber>")), responseText02);
//Console.WriteLine(responseText);
Console.Clear();
Console.WriteLine("(" + percentage + ") " + innerpercentage + "/" + innerpercentagedone + ". Total: " + percentage + " / " + percentagedone);
innerpercentage++;
}
}
//string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(#"D:\Downloads\edasltxmlrequest\ConsoleApplication1\ConsoleApplication1\bin\Debug\test\" + r + ".xml"))
{
outputFile.WriteLine(responseText);
}
//Console.Clear();
//Console.WriteLine(percentage + " / " + percentagedone);
percentage++;
innerpercentage = 1;
//Console.WriteLine(responseText);
}
}
Console.WriteLine("--------");
Console.ReadLine();
}
}
}
So I wanted to ask if it's possible to make it run as a web app (http://www.amazingwebsite.com/ThisThingIWroteRightThere.php
I have searched the web, and is new to this still. Please have some patience with me.
What I want to do is this:
- I have a TreeView called "treeTO".
- I connect to my FTP Server and I want to populate everything here (the directories, sub directories, and the files, whatever it may be) in the treeview.
- This is my code I have so far:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ActiveServer.Server + "/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(ActiveServer.UserName, ActiveServer.Password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
-This returns me the following text: Logs, Data, and WwwRoot.
I struggle to add this to the treeview and then loop through the folders to add everything to the treeview.
So here´s my working Solution for you!
Of course you have to replace the Value of "root" with the rootURL of your FTP-Server and in the Method GetWebRequest() replace "username" and "password" with your Credentials!
You need this Class to Hold Details
public class FTPListDetail
{
public bool IsDirectory
{
get
{
return !string.IsNullOrWhiteSpace(Dir) && Dir.ToLower().Equals("d");
}
}
internal string Dir { get; set; }
public string Permission { get; set; }
public string Filecode { get; set; }
public string Owner { get; set; }
public string Group { get; set; }
public string Name { get; set; }
public string FullPath { get; set; }
}
and here is the Code-Behind for your WinForm-App
private void button1_Click(object sender, EventArgs e)
{
var root = "ftp://ftp.yourFTPServer.at";
treeView1.Nodes.Clear();
treeView1.Nodes.Add(CreateDirectoryNode(root, "root"));
}
private TreeNode CreateDirectoryNode(string path, string name)
{
var directoryNode = new TreeNode(name);
var directoryListing = GetDirectoryListing(path);
var directories = directoryListing.Where(d => d.IsDirectory);
var files = directoryListing.Where(d => !d.IsDirectory);
foreach (var dir in directories)
{
directoryNode.Nodes.Add(CreateDirectoryNode(dir.FullPath, dir.Name));
}
foreach (var file in files)
{
directoryNode.Nodes.Add(new TreeNode(file.Name));
}
return directoryNode;
}
public IEnumerable<FTPListDetail> GetDirectoryListing(string rootUri)
{
var CurrentRemoteDirectory = rootUri;
var result = new StringBuilder();
var request = GetWebRequest(WebRequestMethods.Ftp.ListDirectoryDetails, CurrentRemoteDirectory);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
if (string.IsNullOrEmpty(result.ToString()))
{
return new List<FTPListDetail>();
}
result.Remove(result.ToString().LastIndexOf("\n"), 1);
var results = result.ToString().Split('\n');
string regex =
#"^" + //# Start of line
#"(?<dir>[\-ld])" + //# File size
#"(?<permission>[\-rwx]{9})" + //# Whitespace \n
#"\s+" + //# Whitespace \n
#"(?<filecode>\d+)" +
#"\s+" + //# Whitespace \n
#"(?<owner>\w+)" +
#"\s+" + //# Whitespace \n
#"(?<group>\w+)" +
#"\s+" + //# Whitespace \n
#"(?<size>\d+)" +
#"\s+" + //# Whitespace \n
#"(?<month>\w{3})" + //# Month (3 letters) \n
#"\s+" + //# Whitespace \n
#"(?<day>\d{1,2})" + //# Day (1 or 2 digits) \n
#"\s+" + //# Whitespace \n
#"(?<timeyear>[\d:]{4,5})" + //# Time or year \n
#"\s+" + //# Whitespace \n
#"(?<filename>(.*))" + //# Filename \n
#"$"; //# End of line
var myresult = new List<FTPListDetail>();
foreach (var parsed in results)
{
var split = new Regex(regex)
.Match(parsed);
var dir = split.Groups["dir"].ToString();
var permission = split.Groups["permission"].ToString();
var filecode = split.Groups["filecode"].ToString();
var owner = split.Groups["owner"].ToString();
var group = split.Groups["group"].ToString();
var filename = split.Groups["filename"].ToString();
myresult.Add(new FTPListDetail()
{
Dir = dir,
Filecode = filecode,
Group = group,
FullPath = CurrentRemoteDirectory + "/" + filename,
Name = filename,
Owner = owner,
Permission = permission,
});
};
return myresult;
}
}
}
private FtpWebRequest GetWebRequest(string method, string uri)
{
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return null;
}
var reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
reqFTP.Method = method;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("yourUser", "yourPassword");
reqFTP.Proxy = null;
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
return reqFTP;
}
There is a reason why no FTP client on the planet preemptively populates a treeview on an FTP server or displays file icons in the treeview. Either one of these will take FOREVER.
What you'll need to do is rethink how you are doing this. When you first connect you are going to want to just populate the tree up until the initial dir and then the initial directory. You do NOT want to put files in your tree view because that will also eat up too much memory in many real world situations. Just add folders (and use the same ICON for >99% of those).
This is what it should look like when you first log in:
/
-home
-joe
-public_html
-docs
-uploads
Notice that, '/' and 'home' are not fully read at this point, we just insert them as placeholders for the user to click on. After that, you just want to add the directories in the clicked folder which aren't there each time the users clicks a folder.
This strategy is going to make life a million times easier. Even if you want to try those more complicated ways to handle this you'll want to start out with the basics.
I used this class
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace Backup_service
{
internal class Ftp_Client
{
//поля
//поле для хранения имени фтп-сервера
private string _Host;
//поле для хранения логина
private string _UserName;
//поле для хранения пароля
private string _Password;
//объект для запроса данных
private FtpWebRequest ftpRequest;
//объект для получения данных
private FtpWebResponse ftpResponse;
//флаг использования SSL
private bool _UseSSL = false;
//фтп-сервер
public string Host
{
get
{
return _Host;
}
set
{
_Host = value;
}
}
//логин
public string UserName
{
get
{
return _UserName;
}
set
{
_UserName = value;
}
}
//пароль
public string Password
{
get
{
return _Password;
}
set
{
_Password = value;
}
}
//Для установки SSL-чтобы данные нельзя было перехватить
public bool UseSSL
{
get
{
return _UseSSL;
}
set
{
_UseSSL = value;
}
}
//Реализеум команду LIST для получения подробного списока файлов на FTP-сервере
public FileStruct[] ListDirectory(string path)
{
if (path == null || path == "")
{
path = "/";
}
//Создаем объект запроса
ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path);
//логин и пароль
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
//команда фтп LIST
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.EnableSsl = _UseSSL;
//Получаем входящий поток
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
//переменная для хранения всей полученной информации
string content = "";
StreamReader sr = new StreamReader(ftpResponse.GetResponseStream(), System.Text.Encoding.ASCII);
content = sr.ReadToEnd();
sr.Close();
ftpResponse.Close();
DirectoryListParser parser = new DirectoryListParser(content);
return parser.FullListing;
}
//метод протокола FTP RETR для загрузки файла с FTP-сервера
public void DownloadFile(string path, string currentfileName)
{
ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path);
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
//команда фтп RETR
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.EnableSsl = _UseSSL;
//Файлы будут копироваться в кталог программы
if (!Directory.Exists(currentfileName))
{
Directory.CreateDirectory(currentfileName);
}
FileStream downloadedFile = new FileStream(currentfileName + #"\" + path.Substring(path.LastIndexOf('/') + 1), FileMode.Create, FileAccess.ReadWrite);
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
//Получаем входящий поток
Stream responseStream = ftpResponse.GetResponseStream();
//Буфер для считываемых данных
byte[] buffer = new byte[1024];
int size = 0;
while ((size = responseStream.Read(buffer, 0, 1024)) > 0)
{
downloadedFile.Write(buffer, 0, size);
}
ftpResponse.Close();
downloadedFile.Close();
responseStream.Close();
}
//метод протокола FTP STOR для загрузки файла на FTP-сервер
public void UploadFile(string path, string fileName)
{
//для имени файла
string shortName = fileName.Remove(0, fileName.LastIndexOf("\\") + 1);
FileStream uploadedFile = new FileStream(fileName, FileMode.Open, FileAccess.Read);
ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path + shortName);
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
ftpRequest.EnableSsl = _UseSSL;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
//Буфер для загружаемых данных
byte[] file_to_bytes = new byte[uploadedFile.Length];
//Считываем данные в буфер
uploadedFile.Read(file_to_bytes, 0, file_to_bytes.Length);
uploadedFile.Close();
//Поток для загрузки файла
Stream writer = ftpRequest.GetRequestStream();
writer.Write(file_to_bytes, 0, file_to_bytes.Length);
writer.Close();
}
//метод протокола FTP DELE для удаления файла с FTP-сервера
public void DeleteFile(string path)
{
ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path);
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
ftpRequest.EnableSsl = _UseSSL;
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
}
//метод протокола FTP MKD для создания каталога на FTP-сервере
public void CreateDirectory(string path, string folderName)
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path + folderName);
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
ftpRequest.EnableSsl = _UseSSL;
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
}
//метод протокола FTP RMD для удаления каталога с FTP-сервера
public void RemoveDirectory(string path)
{
string filename = path;
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path);
ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
ftpRequest.EnableSsl = _UseSSL;
ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
}
}
//Для парсинга полученного детального списка каталогов фтп-сервера
//Структура для хранения детальной информации о файле или каталоге
public struct FileStruct
{
public string Flags;
public string Owner;
public bool IsDirectory;
public string CreateTime;
public string Name;
}
public enum FileListStyle
{
UnixStyle,
WindowsStyle,
Unknown
}
//Класс для парсинга
public class DirectoryListParser
{
private List<FileStruct> _myListArray;
public FileStruct[] FullListing
{
get
{
return _myListArray.ToArray();
}
}
public FileStruct[] FileList
{
get
{
List<FileStruct> _fileList = new List<FileStruct>();
foreach (FileStruct thisstruct in _myListArray)
{
if (!thisstruct.IsDirectory)
{
_fileList.Add(thisstruct);
}
}
return _fileList.ToArray();
}
}
public FileStruct[] DirectoryList
{
get
{
List<FileStruct> _dirList = new List<FileStruct>();
foreach (FileStruct thisstruct in _myListArray)
{
if (thisstruct.IsDirectory)
{
_dirList.Add(thisstruct);
}
}
return _dirList.ToArray();
}
}
public DirectoryListParser(string responseString)
{
_myListArray = GetList(responseString);
}
private List<FileStruct> GetList(string datastring)
{
List<FileStruct> myListArray = new List<FileStruct>();
string[] dataRecords = datastring.Split('\n');
//Получаем стиль записей на сервере
FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
foreach (string s in dataRecords)
{
if (_directoryListStyle != FileListStyle.Unknown && s != "")
{
FileStruct f = new FileStruct();
f.Name = "..";
switch (_directoryListStyle)
{
case FileListStyle.UnixStyle:
f = ParseFileStructFromUnixStyleRecord(s);
break;
case FileListStyle.WindowsStyle:
f = ParseFileStructFromWindowsStyleRecord(s);
break;
}
if (f.Name != "" && f.Name != "." && f.Name != "..")
{
myListArray.Add(f);
}
}
}
return myListArray;
}
//Парсинг, если фтп сервера работает на Windows
private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
{
//Предположим стиль записи 02-03-04 07:46PM <DIR> Append
FileStruct f = new FileStruct();
string processstr = Record.Trim();
//Получаем дату
string dateStr = processstr.Substring(0, 8);
processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();
//Получаем время
string timeStr = processstr.Substring(0, 7);
processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();
f.CreateTime = dateStr + " " + timeStr;
//Это папка или нет
if (processstr.Substring(0, 5) == "<DIR>")
{
f.IsDirectory = true;
processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
}
else
{
string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
processstr = strs[1];
f.IsDirectory = false;
}
//Остальное содержмое строки представляет имя каталога/файла
f.Name = processstr;
return f;
}
//Получаем на какой ОС работает фтп-сервер - от этого будет зависеть дальнейший парсинг
public FileListStyle GuessFileListStyle(string[] recordList)
{
foreach (string s in recordList)
{
//Если соблюдено условие, то используется стиль Unix
if (s.Length > 10
&& Regex.IsMatch(s.Substring(0, 10), "(-|d)((-|r)(-|w)(-|x)){3}"))
{
return FileListStyle.UnixStyle;
}
//Иначе стиль Windows
else if (s.Length > 8
&& Regex.IsMatch(s.Substring(0, 8), "[0-9]{2}-[0-9]{2}-[0-9]{2}"))
{
return FileListStyle.WindowsStyle;
}
}
return FileListStyle.Unknown;
}
//Если сервер работает на nix-ах
private FileStruct ParseFileStructFromUnixStyleRecord(string record)
{
//Предположим. тчо запись имеет формат dr-xr-xr-x 1 owner group 0 Nov 25 2002 bussys
FileStruct f = new FileStruct();
if (record[0] == '-' || record[0] == 'd')
{// правильная запись файла
string processstr = record.Trim();
f.Flags = processstr.Substring(0, 9);
f.IsDirectory = (f.Flags[0] == 'd');
processstr = (processstr.Substring(11)).Trim();
//отсекаем часть строки
_cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
f.CreateTime = getCreateTimeString(record);
//Индекс начала имени файла
int fileNameIndex = record.IndexOf(f.CreateTime) + f.CreateTime.Length;
//Само имя файла
f.Name = record.Substring(fileNameIndex).Trim();
}
else
{
f.Name = "";
}
return f;
}
private string getCreateTimeString(string record)
{
//Получаем время
string month = "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)";
string space = #"(\040)+";
string day = "([0-9]|[1-3][0-9])";
string year = "[1-2][0-9]{3}";
string time = "[0-9]{1,2}:[0-9]{2}";
Regex dateTimeRegex = new Regex(month + space + day + space + "(" + year + "|" + time + ")", RegexOptions.IgnoreCase);
Match match = dateTimeRegex.Match(record);
return match.Value;
}
private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
{
int pos1 = s.IndexOf(c, startIndex);
string retString = s.Substring(0, pos1);
s = (s.Substring(pos1)).Trim();
return retString;
}
}
}
and this void
//Построение дерева файловой системы ftp сервера
private static void ListDirectory(TreeView treeView, string Host, string UserName, string password)
{
Ftp_Client ftp = new Ftp_Client();
ftp.Host = Host;
ftp.UserName = UserName;
ftp.Password = password;
treeView.Nodes.Clear();
var stack = new Stack<TreeNode>();
var rootDirectory = DOMAIN;
var node = new TreeNode(rootDirectory) { Tag = "/" };
stack.Push(node);
while (stack.Count > 0)
{
try
{
var currentNode = stack.Pop();
var directoryInfo = ftp.ListDirectory((string)currentNode.Tag);
foreach (var directory in directoryInfo)
{
if (directory.IsDirectory && directory.Name!="?") {
var childDirectoryNode = new TreeNode(directory.Name) { Tag = currentNode.Tag+directory.Name+'/'};
currentNode.Nodes.Add(childDirectoryNode);
stack.Push(childDirectoryNode);
}
}
foreach (var file in directoryInfo)
if (!file.IsDirectory && file.Name != "?")
currentNode.Nodes.Add(new TreeNode(file.Name) { Tag = currentNode.Tag + file.Name + "/f"}); ; //пометка f в конце пути означает, что это файл!
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
treeView.Nodes.Add(node);
}
calling by
ListDirectory(treeView1,DOMAIN,USER,PASS);
Is there a way to have a distance between 2 addresses calculated by Google Maps?
How?
If you just have two addreses first try to get lat lan by GEOCODING and then there are many methods to get distance in between.
OR
if you dont need geocoding and want a CS SOLUTION try this :
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
//string from = origin.Text;
//string to = destination.Text;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
//string requesturl = #"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false";
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
return distance;
//ResultingDistance.Text = distance;
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
OR
if you dont want to mess with google and need only AIR DISTANCE,Try this :
public decimal calcDistance(decimal latA, decimal longA, decimal latB, decimal longB)
{
double theDistance = (Math.Sin(DegreesToRadians(latA)) *
Math.Sin(DegreesToRadians(latB)) +
Math.Cos(DegreesToRadians(latA)) *
Math.Cos(DegreesToRadians(latB)) *
Math.Cos(DegreesToRadians(longA - longB)));
return Convert.ToDecimal((RadiansToDegrees(Math.Acos(theDistance)))) * 69.09M * 1.6093M;
}
NB: As of June 11th 2018 this approach will no longer work as Google has disabled keyless access to the Maps API. If you wish to use this approach you will have to sign up for their cloud platform and enable billing.
You can do this using the Google Directions API, you pass the start/end locations to the API as address strings or coordinates and Google will do all the leg work for you.
Routes are made up of various legs based on how many way points you specify. In your scenario (0 way points) you should only have 1 leg which should have an estimated distance property.
I have fixed the code from the answer above for it to work with google key.
Get you API key for google maps
Install Nuget package: Newtonsoft.Json
3.
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
string key = "YOUR KEY";
string url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&key=" + key;
url = url.Replace(" ", "+");
string content = fileGetContents(url);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("https:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
Send a request to the Distance Matrix service or to the Directions-Service (when you need the distance of a route)
And I did this: but it return an empty string.
url = "http://maps.googleapis.com/maps/api/directions/json?origin=3320, rue de verdun, verdun&destination=379, 19e avenue, La Guadeloupe, G0M 1G0&sensor=false"
public string fileGetContents(string url)
{
string text = "";
var webRequest = HttpWebRequest.Create(url);
IAsyncResult asyncResult = null;
asyncResult = webRequest.BeginGetResponse(
state =>
{
var response = webRequest.EndGetResponse(asyncResult);
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
}, null
);
return text;
}