diff --git a/apps/files_external/lib/sftp.php b/apps/files_external/lib/sftp.php
index fb1ecd5463517945760ffdfe9160d3c79c9e0c80..7c5aed5aa06b04f21e69077c28f3dc17352a6a7a 100644
--- a/apps/files_external/lib/sftp.php
+++ b/apps/files_external/lib/sftp.php
@@ -94,15 +94,17 @@ class SFTP extends \OC\Files\Storage\Common {
 	private function writeHostKeys($keys) {
 		try {
 			$keyPath = $this->hostKeysPath();
-			$fp = fopen($keyPath, 'w');
-			foreach ($keys as $host => $key) {
-				fwrite($fp, $host . '::' . $key . "\n");
+			if ($keyPath && file_exists($keyPath)) {
+				$fp = fopen($keyPath, 'w');
+				foreach ($keys as $host => $key) {
+					fwrite($fp, $host . '::' . $key . "\n");
+				}
+				fclose($fp);
+				return true;
 			}
-			fclose($fp);
-			return true;
 		} catch (\Exception $e) {
-			return false;
 		}
+		return false;
 	}
 
 	private function readHostKeys() {