Search for content from an online file

0
string nome, idade, valores;

WebClient WEBC = new WebClient();

public void Exemplo()
{
    valores = WEBC.DownloadString("https://pastebin.com/raw/r4GjhKQ3");
}

I want to get the values of the name and age after the '=' of the 'values' variable ( link ) and then I want to save those values in the variables I declared above (name and age).

EDIT

What if I need to get more users? For example:

{
    "Users":[{"Nome":"Pedro","Idade":"25"},{"Nome":"Lucas","Idade":"19"}]
}
    
asked by anonymous 17.06.2018 / 05:02

1 answer

3

First, I recommend that you use a well-defined text / file structure to save your information, such as JSON. This will make the processing of your data simpler and more convenient to manipulate.

JSON is basically a lightweight information / data exchange format between systems and means JavaScript Object Notation. Do not be alarmed by "JavaScript" as it is not only with Javascript that we can use this type of file. I recommend you read a little more about the subject and understand how this type of file works and its structure.

Recommended reading : What is JSON?

Transforming your file into JSON

Replace the contents of your User: (name = Peter, age = 25) by:

{
    "Nome" : "Pedro",
    "Idade" : "25"
}

You can save the file in .json format instead of .txt and send it to Pastebin . That done, we can go to the code part.

Installing the library that will handle your JSON file

In Visual Studio (I believe you are using it to encode in C #), within your project, right-click References and then select the Manage NuGet Packages :

Onceyouhavedonethis,selectBrowse,inthetextboxtype"json", select the item Newtonsoft.Json and then click install:

CreatingthetemplateclassforyourJSONfile

Withinyourproject,addaclassthatwillbeusedasatemplateforyourJSONfile.Givenyourquestion,we'retalkingaboutauser,socreateaclasscalledUsuariothathasthefollowingstructure:

publicclassUsuario{publicstringNome{get;set;}publicstringIdade{get;set;}}

NotethatthenameoftheclasspropertiesareexactlythesameasthenamesthatareinthestructureofyourJSON.InthisfirstmomentanduntilyoubecomefamiliarwithJSON,wehavetokeepitthatway.

ManipulatingYourJSONFile

Nowthatwehaveourenvironmentready,wecanbegintomanipulatethedatafromourJSONfile.

Inthesameclassthatputthecodeinthequestion,putthefollowingusingdirectiveatthetopofyourclass:

usingNewtonsoft.Json;

Now,downloadyourfileandmakeitanobjectoftypeUsuario,whichwasthemodelclasswecreatedearlier:

WebClientweb=newWebClient();stringresult=web.DownloadString("https://pastebin.com/raw/j0P175Wq");

Usuario usuario = JsonConvert.DeserializeObject<Usuario>(result);

The link I used is from a file I put in Pastebin to use as an example. Remember to change the link to your file link.

When you run the code above, you will notice that the content of your JSON file that was in Pastbin was transformed into an object of type Usuario which in the above code I called usuario . With this, we can access the object and check its Nome and Idade properties, which will contain exactly what is in your JSON file:

Finally,putthecontentoftheobjectusuario,intothedesiredvariables:

stringnome=usuario.Nome;stringidade=usuario.Idade;

Andifyouwanttoaddmoreusers?

FromthetemplateIexplained,only1userperfilewouldbeallowed(Ihopedyourquestionwouldcomeupsothatyoucouldconcludethequestiondefinitively).Nowlet'smakethemodificationssothatyoucanfindmoreusersofthefile.

Ihavealreadycreatedaverynicestructureforyourfile,let'skeepitandmodifyonlyourcode.

Givenitsstructure,thefilehasaUsersobjectthatisalistofusers,thatis,alistofourclassUsuariopreviouslycreated.

Let'snowcreateanotherclass,calledArquivo,whichwillserveasthenewJSONfiletemplate:

publicclassArquivo{publicList<Usuario>Users{get;set;}}

NotethatthisnewclasshastheUsersproperty,whichisexactlythesameasthenameyougavetoyourlistofusersinyourJSONfile.AlsonotethatthepropertyisaUsuariolist.RemembertousetheusingSystem.Collections.GenericdirectivetoaccessList.

Onceyou'vedonethis,modifyyourcodesnippetthatdoestheJSONfilemanipulationtolooklikethis:

WebClientweb=newWebClient();stringresult=web.DownloadString("https://pastebin.com/raw/j0P175Wq");

Arquivo arquivo = JsonConvert.DeserializeObject<Arquivo>(result);

List<Usuario> usuarios = arquivo.Users;

Here, notice that it is no longer the class Usuario that serves as the template for the JSON file, but the class Arquivo through the line JsonConvert.DeserializeObject<Arquivo> .

When executing the above code, you will notice that the user list is inside the arquivo object and within the Users property.

    
17.06.2018 / 06:28