コード例 #1
0
		public TiResponse process(TiRequestParams data) {
			if (!data.ContainsKey("url")) {
				throw new Exception("Download Handler Exception: Request missing 'url' param");
			}

			string url = (string)data["url"];

			if (!url.StartsWith("http://") && !url.StartsWith("https://")) {
				throw new Exception("Download Handler Exception: 'url' param must start with 'http://' or 'https://'");
			}

			string saveTo = "";
			int p;

			if (data.ContainsKey("saveTo")) {
				saveTo = (string)data["saveTo"];
			} else {
				// try to determine the filename based on the URL
				p = url.LastIndexOf('/');
				if (p > 8 && p != -1) { // make sure the last / is after the ://
					saveTo = url.Substring(p + 1);
				} else {
					throw new Exception("Download Handler Exception: Request missing 'saveTo' param");
				}
			}

			if (saveTo == null || saveTo == "") {
				throw new Exception("Download Handler Exception: Invalid 'saveTo' param");
			}

			saveTo = saveTo.Replace('\\', '/');

			IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

			p = saveTo.LastIndexOf('\\');
			if (p != -1) {
				string dir = saveTo.Substring(0, p);
				try {
					if (!isf.DirectoryExists(dir)) {
						isf.CreateDirectory(dir);
					}
				} catch (IsolatedStorageException ise) {
					throw new Exception("Download Handler Exception: Unable to create destination directory '" + dir + "' because of insufficient permissions or the isolated storage has been disabled or removed");
				}
			}

			if (isf.FileExists(saveTo)) {
				if (data.ContainsKey("overwrite") && (bool)data["overwrite"]) {
					isf.DeleteFile(saveTo);
				} else {
					throw new Exception("Download Handler Exception: File '" + saveTo + "' already exists");
				}
			}

			IsolatedStorageFileStream fileStream = null;

			try {
				fileStream = isf.CreateFile(saveTo);
			} catch (IsolatedStorageException ise) {
				throw new Exception("Download Handler Exception: Unable to create file '" + saveTo + "' because the isolated storage has been disabled or removed");
			} catch (DirectoryNotFoundException dnfe) {
				throw new Exception("Download Handler Exception: Unable to create file '" + saveTo + "' because the directory does not exist");
			} catch (ObjectDisposedException dnfe) {
				throw new Exception("Download Handler Exception: Unable to create file '" + saveTo + "' because the isolated storage has been disposed");
			}

			TiResponse response = new TiResponse();
			DownloadFile df = new DownloadFile();
			response["handle"] = InstanceRegistry.createHandle(df);
			df.downloadFileAsync(url, fileStream);

			return response;
		}