简体   繁体   中英

Replace image path to base64 string with several containing string

I have a string containing " https://tryout.pendukasi.id/upload/ " and I want to replace every string that contains " https://tryout.pendukasi.id/upload/ " to "data:image/jpeg; base64".

Code:

foreach (StorageFile file in files)
{
    string soalP = file.Path;
    if (question.Pertanyaan.ToString().Contains("https://tryout.pendidikan.id/upload/"))
    {
        byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
            string base64ImageRepresentation = Convert.ToBase64String(imageArray);
            soal = Regex.Replace(question.Pertanyaan.ToString(), "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
    }
}

I am having a problem, if the string contains one " https://tryout.pendukasi.id/upload/ ", then the string is successfully replaced, but if it contains several " https://tryout.pendukasi.id/upload/ ", for example: "<p>Perhatikan ayat-ayat Surat al-Falaq berikut ini:<br /><img src=\"https.//tryout.pendidikan.id/upload/3-1:JPG\" /><br /><img src=\"https.//tryout.pendidikan.id/upload/3-2:JPG\" /><br /><img src=\"https.//tryout.pendidikan.id/upload/3-3:JPG\" /><br /><img src=\"https.//tryout.pendidikan.id/upload/3-4:JPG\" /><br /><img src=\"https.//tryout.pendidikan.id/upload/3-5;JPG\" /><br />Urutan ayat dalam Surat al-Falaq yang benar adalah &hellip..</p>" , then the string was not successfully changed. How to solve this problem?

It happens because you're replacing file by file, and it's previous change keeps being changed by:

soal = Regex.Replace(question.Pertanyaan.ToString(), "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);

An approach would be be saving your regex replaced string to a variable. By doing so, your replacements wouldn't be overwritten:

string soal = question.Pertanyaan.ToString();

foreach (StorageFile file in files)
{
    string soalP = file.Path;
    if (soal.Contains("https://tryout.pendidikan.id/upload/"))
    {
        byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
            string base64ImageRepresentation = Convert.ToBase64String(imageArray);
            soal = Regex.Replace(soal, "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM