Skip to content

一些技巧

文件操作

用完记得释放

注意:FileAccess 被释放时会自动关闭,释放发生在离开作用域或被赋值为 null 时。在 C# 中,使用完后必须弃置该引用,可以使用 using 语句或直接调用 Dispose 方法。

gdscript

static func load_string(path:String,encrypt_key:String="") -> String:
	if not FileAccess.file_exists(path):
		return ""
	else:
		var file:FileAccess
		if encrypt_key.is_empty():
			file = FileAccess.open(path, FileAccess.READ)
		else:
			file = FileAccess.open_encrypted_with_pass(path,FileAccess.READ,encrypt_key)
		if file == null:
			print(FileAccess.get_open_error())
			return	""


		var text = file.get_as_text()
		file.close()
		# 确保进行垃圾回收
		file = null
		return text

static func save_string(path:String,content:String,encrypt_key:String=""):
	var file:FileAccess
	if encrypt_key.is_empty():
		file = FileAccess.open(path, FileAccess.WRITE)
	else:
		file = FileAccess.open_encrypted_with_pass(path,FileAccess.WRITE,encrypt_key)
	file.store_string(content)
	file.close()
	file = null