Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Last active July 19, 2019 15:18
Show Gist options
  • Save bjoerntx/3c468ed940ca519413ed246ea4fd1637 to your computer and use it in GitHub Desktop.
Save bjoerntx/3c468ed940ca519413ed246ea4fd1637 to your computer and use it in GitHub Desktop.
public class DictionaryController : ApiController
{
// returns all user dictionaries in the specific folder
[System.Web.Http.HttpGet]
public HttpResponseMessage UserDictionaryFilenames()
{
var sFilenames = System.IO.Directory
.EnumerateFiles(System.Web.Hosting.HostingEnvironment.MapPath("~/Dictionaries/"),
"*.txd", System.IO.SearchOption.TopDirectoryOnly)
.Select(System.IO.Path.GetFileName);
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent<string[]>(sFilenames.ToArray(),
new JsonMediaTypeFormatter())
};
}
// loads a specific dictionary by filename
[System.Web.Http.HttpGet]
public HttpResponseMessage LoadUserDictionary(string filename)
{
UserDictionary userDictionary = new UserDictionary() {
language = "en-US",
name = filename
};
// read all lines from the dictionary
string[] sDictionaryLines = System.IO.File.ReadAllLines(
System.Web.Hosting.HostingEnvironment.MapPath("~/Dictionaries/" + filename));
// skip the first entry (encoding)
userDictionary.words = sDictionaryLines.Skip(1).ToArray();
// return the object
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent<UserDictionary>(userDictionary,
new JsonMediaTypeFormatter())
};
}
// saves a specific dictionary
[System.Web.Http.HttpPost]
public HttpResponseMessage SaveUserDictionary([FromBody] UserDictionary dictionary)
{
// get all words and save the dictionary
List<string> dictionaryLines = new List<string>();
dictionaryLines.Add("SET iso-8859-1");
dictionaryLines.AddRange(dictionary.words);
System.IO.File.WriteAllLines(System.Web.Hosting.HostingEnvironment.MapPath(
"~/Dictionaries/" + dictionary.name), dictionaryLines);
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent<string>("UserDictionary " +
dictionary.name + " successfully saved.", new JsonMediaTypeFormatter())
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment