2
Answers

Defining a Constructor in a WebService

Milly Haywire

Milly Haywire

10y
902
1
Hi, 

I need to define this code;

protected void Page_Load(object sender, EventArgs e)
    {
        using (var reader = new StreamReader(File.OpenRead(@"C:/dictionary.csv")))
        {
            while (!reader.EndOfStream)
            {
                string[] tokens = reader.ReadLine().Split(';');
                _dictionary[tokens[0]] = tokens[1];
            }
        }
    }

In a webservice but I can't get it to work. At current my code looks like this;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service() { }
    private Dictionary<string, string> _dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    protected void Page_Load(object sender, EventArgs e)
    {
        using (var reader = new StreamReader(File.OpenRead(@"C:/dictionary.csv")))
        {
            while (!reader.EndOfStream)
            {
                string[] tokens = reader.ReadLine().Split(';');
                _dictionary[tokens[0]] = tokens[1];
            }
        }
    }
    [WebMethod]
    public string Translate(string input)
    {
        string output;
        if (_dictionary.TryGetValue(input, out output))
            return output;

        throw new Exception("Invalid input, please try again.");
    }
}
    

Can anyone help? 

Answers (2)