G
G
Grasinki2017-10-30 18:36:30
C++ / C#
Grasinki, 2017-10-30 18:36:30

Saving and reading cookies from a text file in xNet?

In general, I keep:

CookieDictionary cookieDictionary = new CookieDictionary(false);
httpRequest.Cookies = cookieDictionary; 
File.AppendAllText("Cookies_" + textBox1.Text + ".txt", Convert.ToString(cookieDictionary));

Reading:
string[] Mass = File.ReadAllLines("Cookies_" + textBox1.Text + ".txt", System.Text.Encoding.Default);
string ref  = Pars(Mass[0] + "", "ref=(.*?);", 1);
string  enabled = Pars(Mass[0] + ";", " enabled=(.*?);", 1);
string se = Pars(Mass[0] + ";", "se=(.*?);", 1);

I substitute:
httpRequest.Cookies = new CookieDictionary
{
  { "ref", ref },
  { "enabled", enabled },
  { "se", se }
};

Question:
Is it possible to somehow create this miracle more gracefully?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2017-10-30
@Grasinki

Use a database :-)
You could try serializing a CookieDictionary , but the Dictionary seems to imply that it won't be easy. If it doesn't work, then you can try to make your own serializable CookieDictionary and use it.
With JSON , there will probably be fewer problems, at least a regular Dictionary can be serialized / deserialized using Newtonsoft.Json without any problems.
You can try with CookieDictionary , something like this:

// получаем json:
string json = JsonConvert.SerializeObject(cookieDictionary);

// получаем экземпляр CookieDictionary из json:
var cookieDictionary2 = JsonConvert.DeserializeObject<CookieDictionary>(json);

If there are problems with serialization and when converting a CookieDictionary instance to a string, the output always turns out to be a string like: key=value; key=value , then you can split this line and get a collection:
// string cookiesRaw = File.ReadAllText(string.Format("Cookies_{0}.txt", textBox1.Text));
string cookiesRaw = "ключ1=значение1; ключ2=значение2";
var cookies = cookiesRaw.Split(';').Select(itm => itm.Split('=')).
              ToDictionary(k => k[0].Trim(), v => v[1].Trim());

The cookies variable will contain a Dictionary instance , which you can try to convert to a CookieDictionary (depends on the implementation), or create and populate a CookieDictionary instance .
httpRequest.Cookies = new CookieDictionary();

foreach(var item in cookies)
{
  httpRequest.Cookies.Add(item.Key, item.Value);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question