autocompleteservice.asmx

来自「《圣殿祭司的ASP.NET 2.0开发详解——使用C#》光盘内容.包含了书籍所含」· ASMX 代码 · 共 69 行

ASMX
69
字号
<%@ WebService Language="C#" Class="Samples.AspNet.AutoCompleteService" %>

using System;
using System.IO;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;

namespace Samples.AspNet
{
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class AutoCompleteService  : System.Web.Services.WebService 
  {
    private static string[] autoCompleteWordList = null;

    [WebMethod]
    public String[] GetWordList(string prefixText, int count)
    {     
      if (autoCompleteWordList == null)
      {
        List<String> words = new List<string>();
        FileStream file = new 
          FileStream(Server.MapPath("~/App_Data/words.txt"), FileMode.Open, 
          FileAccess.Read);
        StreamReader reader = new StreamReader(file);
        String word;
        while ((word = reader.ReadLine()) != null)
        {
          words.Add(word);
        }
        file.Close();
        autoCompleteWordList = words.ToArray();
        Array.Sort(autoCompleteWordList, new CaseInsensitiveComparer());
      }

      int index = Array.BinarySearch(autoCompleteWordList, prefixText, new CaseInsensitiveComparer());
      if (index < 0)
      {
        index = ~index;
      }

      int matchingCount;
      for (matchingCount = 0;matchingCount < count && index + matchingCount < autoCompleteWordList.Length;matchingCount++)
      {
        if (!autoCompleteWordList[index + 
          matchingCount].StartsWith(prefixText, 
          StringComparison.CurrentCultureIgnoreCase))
        {
          break;
        }
      }

      String[] returnValue = new string[matchingCount];
      if (matchingCount > 0)
      {
        Array.Copy(autoCompleteWordList, index, returnValue, 0, 
          matchingCount);
      }
      return returnValue;
    }
      
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?