AddPerson.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // See CSHARP-README.txt for information and build instructions.
  2. using System;
  3. using System.IO;
  4. using Tutorial;
  5. class AddPerson {
  6. // This function fills in a Person message based on user input.
  7. static Person PromptForAddress(TextReader input, TextWriter output) {
  8. Person.Builder person = Person.CreateBuilder();
  9. output.Write("Enter person ID: ");
  10. person.Id = int.Parse(input.ReadLine());
  11. output.Write("Enter name: ");
  12. person.Name = input.ReadLine();
  13. output.Write("Enter email address (blank for none): ");
  14. string email = input.ReadLine();
  15. if (email.Length > 0) {
  16. person.Email = email;
  17. }
  18. while (true) {
  19. output.Write("Enter a phone number (or leave blank to finish): ");
  20. string number = input.ReadLine();
  21. if (number.Length == 0) {
  22. break;
  23. }
  24. Person.Types.PhoneNumber.Builder phoneNumber =
  25. Person.Types.PhoneNumber.CreateBuilder().SetNumber(number);
  26. output.Write("Is this a mobile, home, or work phone? ");
  27. String type = input.ReadLine();
  28. switch (type) {
  29. case "mobile":
  30. phoneNumber.Type = Person.Types.PhoneType.MOBILE;
  31. break;
  32. case "home":
  33. phoneNumber.Type = Person.Types.PhoneType.HOME;
  34. break;
  35. case "work":
  36. phoneNumber.Type = Person.Types.PhoneType.WORK;
  37. break;
  38. default:
  39. Console.WriteLine("Unknown phone type. Using default.");
  40. break;
  41. }
  42. person.AddPhone(phoneNumber);
  43. }
  44. return person.Build();
  45. }
  46. // Main function: Reads the entire address book from a file,
  47. // adds one person based on user input, then writes it back out to the same
  48. // file.
  49. public static int Main(string[] args) {
  50. if (args.Length != 1) {
  51. Console.Error.WriteLine("Usage: AddPerson ADDRESS_BOOK_FILE");
  52. return -1;
  53. }
  54. AddressBook.Builder addressBook = AddressBook.CreateBuilder();
  55. if (File.Exists(args[0])) {
  56. using (Stream file = File.OpenRead(args[0])) {
  57. addressBook.MergeFrom(file);
  58. }
  59. } else {
  60. Console.WriteLine("{0}: File not found. Creating a new file.", args[0]);
  61. }
  62. // Add an address.
  63. addressBook.AddPerson(PromptForAddress(Console.In, Console.Out));
  64. // Write the new address book back to disk.
  65. using (Stream output = File.OpenWrite(args[0])) {
  66. addressBook.Build().WriteTo(output);
  67. }
  68. return 0;
  69. }
  70. }